繁体   English   中英

多行清洗原始数据 header

[英]Cleaning raw data with multi-line header

我需要组织从 excel 数据库导入的数据,问题是它有多行 header 与客户信息,然后是很多行与付款信息。 我想从 header 获取数据并创建一个包含合同编号和操作情况的新列(它们都在标题中)并将此信息放在每条付款行中,这样我就可以轻松切片 dataframe。

我曾经使用 Excel,我所做的是在列中创建一个带有 IF 语句的公式,该公式将识别 header 中的合同编号,如果没有找到将复制上面的单元格。 我的代码在一列中标识了一个键字符串,然后从单元格之间的预定义距离获取合同值和状态。 您可以在我的 python for 循环中看到它。

python for 循环变得太慢,这是我放弃 excel 的主要原因,所以我希望在 python 中有更快的方法。

我还尝试使用.where() function,但我找不到从 header 获取合同和状态信息的正确方法。

我使用的 for 循环是这样的:

report = pd.read_excel('report_filename.xls', header = None)

for j in range(report.shape[0]):
    if str(report.loc[j,1])[0:7] == 'Extract':
        contract = report.loc[j + 1, 3]
        status = report.loc[j + 7, 1]

    report.loc['contract #', j] = contrato
    report.loc['status'] = status

# Here is the final version of the code i used:

report = pd.read_excel('report_filename.xls', header = None)
report['Contract #'] = None
report['Status'] = None

for i, row in report.iterrows():
    if str(row[1]).lower().startswith('extract'):
        report.at[i, 'Contract #'] = report.at[i+1, 3]
        report.at[i, 'Status'] = report.at[i+7, 1]

report['Contract #'] = report['Contract #'].ffill(axis = 0)
report['Status'] = report['Status'].ffill(axis = 0)


report = report[report['Status'] != 'Inactive']

你能用 pandas.iterrows 吗?

import pandas as pd

report = pd.read_excel('report_filename.xls', header = None)
newreport = report
newreport['Contract #'] = ''
newreport['Status'] = ''

for i, row in report.iterrows():
    if row[1].lower().startswith('extract'):
        newreport.at[i, 'Contract #'] = report.at[i+1, 3]
        newreport.at[i, 'Status'] = report.at[i+7, 1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM