代码之家  ›  专栏  ›  技术社区  ›  iBeMeltin

查找读取csv数据的起点

  •  0
  • iBeMeltin  · 技术社区  · 1 年前

    我每天都会收到一个csv文件,其中包含用于计算的数据。我想用熊猫来组织数据。我的问题是要读取的数据不是从文件的第一行开始的。数据也不是每次都在同一行开始,所以我不能在read_csv()方法中使用skiprows参数。

    数据确实有一些指示数据起始位置的指标。

    例如,这就是csv文件开头的样子。我只想从第一列标题“交易类型”开始:

    Counterparty Name
    ID Number
    
    .
    .
    .
    
    Asset
    USD.HO
    USD.LCO
    USD.RB
    
    Cpty:
    Product:
    
    [Deal Type] [column] ... ... ...
    [here the data begins]
    

    我如何解析文件并找到第一个列标题并从那一行开始?列标题“交易类型”始终是第一列。

    3 回复  |  直到 1 年前
        1
  •  2
  •   TheHungryCub    1 年前

    逐行读取文件,直到找到包含目标标头的行,然后使用 pd.read_csv() 具有 skiprows 参数开始从该行读取文件。

    import pandas as pd
    
    def find_starting_line(file_path, target_header):
        with open(file_path, 'r') as file:
            for line_num, line in enumerate(file):
                if target_header in line:
                    return line_num
    
    def read_csv_with_header(file_path, header):
        starting_line = find_starting_line(file_path, header)
        if starting_line is not None:
            return pd.read_csv(file_path, skiprows=starting_line, header=None)
        else:
            print(f"Header '{header}' not found in the file.")
            return None
    
    # Example usage
    file_path = 'your_file.csv'
    header_to_find = 'Deal Type'
    df = read_csv_with_header(file_path, header_to_find)
    if df is not None:
        print(df)
    
        2
  •  0
  •   NISHITH    1 年前

    您可能需要解析csv文件,并从您想要csv的行号中读取

    import pandas as pd
    def find_start_line(filename, column_name):
    with open(filename, 'r') as file:
        for line_number, line in enumerate(file, 1):
            if column_name in line:
                return line_number
    

    一旦您有了行号,请阅读csv:

    int skip_num = find_start_line(file.csv,"Deal Type")
    df = pd.read_csv("file.csv",skiprows=skip_num-1)
    df.head()
    
        3
  •  0
  •   JonSG    1 年前

    我认为你不需要把文件读两遍。只要读一遍,跳过你不想要的行,直到你找到你的地标。

    import pandas
    import io
    
    data = """
    Counterparty Name
    ID Number
    
    .
    .
    .
    
    Asset
    USD.HO
    USD.LCO
    USD.RB
    
    Cpty:
    Product:
    
    [Deal Type] [column] ... ... ...
    1,2,3
    4,5,6
    """.strip()
    
    with io.StringIO(data) as file_in:
        for line in file_in:
            if line.startswith("[Deal Type]"):
                break
        
        print(pandas.read_csv(file_in))