提问者:小点点

如何在电子表格中的字符串标题后选择Pandas中的行?


我有一个.CSV文件,它具有以下结构(在Excel上查看时),其中具有占用单个单元格的唯一节标题(字符串),后跟一个包含列名和数据的块。

这种格式在整个Excel电子表格中重复出现。请注意,每个部分都有不同的名称和编号,以及可变的行数。

示例:

    Daily Statements                                    

    Date        Desc    Customer ID   Phone          Status
    12/21/21    aaa     1             123-123-1231   OK 
    12/21/21    aaa     2             333-123-1231   OK
    12/21/21    bbb     3             222-123-1231   OK
    12/21/21    bbb     3             444-123-1231   OK
                                              <===== one empty row separates sections
    Account History                                 
    Date        Time    Type    Ref #   Balance
    12/21/21    1:00:00 BAL     456     $0.01 
    12/21/21    1:00:00 BAL     445     $0.01
    12/21/21    1:00:00 BAL     645     $0.01
                                              <===== one empty row separates sections
    Order History                                   
    ID    Date      Ref #
    1     12/21/21  777  
    2     12/21/21  888 
    3     12/21/21  999
    4     12/21/21  9995

我的目标是仅提取帐户历史记录中的行:

    Date        Time    Type    Ref #   Balance
    12/21/21    1:00:00 BAL     456     $0.01 
    12/21/21    1:00:00 BAL     445     $0.01
    12/21/21    1:00:00 BAL     645     $0.01

但是,我无法找到在Pandas中有效的方法,因为我需要使用字符串“帐户历史记录”作为锚来指示感兴趣的行。

你知道这是如何实现的吗?


共1个答案

匿名用户

我看不出仅使用Pandas就可以直接做到这一点。为什么不先将文件作为文本文件读取以查找感兴趣的行,然后再使用Pandas仅导入这些行?

with open(file, 'r') as f:
    # read until the line "Account History"
    for line_n, line_content in enumerate(f):
        if "Account History" in line_content:
            break
    start_row = line_n + 1

    # continue reading, and find the following new line
    for line_n, line_content in enumerate(f):
        if line_content == '\n':
            break
    tab_size = line_n - 1

# import the dataframe, just from the target lines
df = pd.read_csv(file, skiprows=start_row, nrows=tab_size)