【问题标题】:Python: merge csv data with differing headersPython:合并具有不同标题的csv数据
【发布时间】:2020-03-29 01:52:34
【问题描述】:

我有一堆软件输出文件,我已将它们处理成类似 csv 的文本文件。我可能已经很难做到这一点,因为我对python库不太熟悉

下一步是将所有这些数据收集到一个 csv 文件中。这些文件有不同的标题,或者排序不同。

假设这是文件 A:

A | B | C | D | id 
0   2   3   2   "A"
...

这是文件 B:

B | A | Z | D | id
4   6   1   0   "B"
...

我希望 append.csv 文件看起来像:

A | B | C | D | Z | id
0   2   3   2       "A"
6   4       0   1   "B"
...

我怎样才能优雅地做到这一点?谢谢大家的回答。

【问题讨论】:

    标签: python csv append


    【解决方案1】:

    您可以使用pandas 将CSV 文件读入DataFrames 并使用concat 方法,然后将结果写入CSV:

    import pandas as pd
    
    df1 = pd.read_csv("file1.csv")
    df2 = pd.read_csv("file2.csv")
    
    df = pd.concat([df1, df2], axis=0, ignore_index=True)
    
    df.to_csv("file.csv", index=False)
    

    【讨论】:

    • 但它应该根据列名追加
    • pd.concat 根据列名隐式附加,不是吗?
    【解决方案2】:

    标准库中的csv 模块提供了可用于执行此操作的工具。 DictReader 类为 csv 文件中的每一行生成列名到值的映射; DictWriter 类会将此类映射写入 csv 文件。

    DictWriter 必须提供列名列表,但不要求每个行映射中都存在所有列名。

    import csv
    
    list_of_files = ['1.csv', '2.csv']
    
    # Collect the column names.
    all_headers = set()
    for file_ in list_of_files:
        with open(file_, newline='') as f:
            reader = csv.reader(f)
            headers = next(reader)
            all_headers.update(headers)
    all_headers = sorted(all_headers)
    
    # Generate the output file.
    with open('append.csv', 'w', newline='') as outfile:
        writer = csv.DictWriter(outfile, fieldnames=all_headers)
        writer.writeheader()
        for file_ in list_of_files:
            with open(file_, newline='') as f:
                reader = csv.DictReader(f)
                writer.writerows(reader)
    
    $ cat append.csv
    A,B,C,D,Z,id
    0,2,3,2,,A
    6,4,,0,1,B
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-20
      • 2018-09-25
      • 2019-12-19
      • 1970-01-01
      • 2020-06-24
      • 2013-04-15
      • 2017-10-05
      • 1970-01-01
      相关资源
      最近更新 更多