Skip to main content
 首页 » 编程设计

Python:将两个 CSV 文件与标题行和匹配值与 DictReader 和 DictWriter 组合

2024年10月25日12虾米哥

我在使用此脚本时遇到了几个不同的问题。目标是直截了当的,我已经找到了一些类似的例子,但还没有任何东西可以让它发挥作用。

  1. 读入基本 CSV 文件 - 这可能因字段名称和字段数量而异
  2. 读入包含一个 ID 的辅助 CSV 文件,该 ID 应与第一个文件中的 ID 列匹配,外加一个新 ID
  3. 创建一个输出 CSV 文件,其中包含文件 1 的列标题和文件 2 的列标题
  4. 打印输出文件中的行,即第一个文件的整行内容,加上第二个文件的匹配 ID。

我正在为如何正确创建输出文件的标题行以及如何将第一个文件中的整行与第二个文件中的匹配键包含在一起而苦恼。我能够让它与阅读器一起工作,但需要切换到 DictReader 以避免对列号进行硬编码,因为它们可以更改。 这是我的尝试。非常感谢任何帮助!

以下是一些示例文件:

示例文件 1: [{'LEGACY_ID': '123', 'Random Column': 'Ignore Me but print me', 'Another Column': 'Ignore me too'}, {'LEGACY_ID': '1234', 'Random Column': 'Ignore Me but print me', 'Another Column': 'Ignore me too'} ... ]

示例文件 2: [{'NEW_ID': 'abc', 'LEGACY_ID': '123'}, {'NEW_ID ': 'abcd', 'LEGACY_ID': '1234'} ... ]

示例输出: [{'LEGACY_ID': '123', 'Random Column': '忽略我但打印我', 'Another Column': '也忽略我', 'NEW_ID': 'abc'}, {'LEGACY_ID': '1234', 'Random Column': '忽略我但打印我', 'Another Column': '也忽略我', 'NEW_ID': 'abcd'} ... ]

import csv 
import string 
with open('legacyFile.csv', 'r') as in_leg, open('NewMapping.csv', 'r') as in_map, open('results.csv', 'wb') as out_res: 
    c1 = csv.DictReader(in_leg, delimiter=',') 
    c2 = csv.DictReader(in_map, delimiter=',')  
    print c1.fieldnames 
    print c2.fieldnames 
    #set headers and write header row to output file 
    File1List = list(c1) 
    File2List = list(c2) 
 
    fieldnames = (str(c1.fieldnames) + str(c2.fieldnames))  
    fieldnames = string.replace(fieldnames, '][', ', ') 
    print (fieldnames) 
 
    c3 = csv.DictWriter(out_res, fieldnames=fieldnames) 
    c3.writeheader() 
 
    print ' c3 ' + c3.fieldnames 
 
    for File1Row in File1List: 
        row = 1 
        found = False 
        print ('ID IS ' + File1Row['ID']) 
        for File2Row in File2List: 
            if File1Row['ID'] == File2Row['LEGACY_ID']: 
                #need to write the entire File1Row to c3, PLUS the matched ID that is found 
                #c3.writerow(File1Row + File2Row['NEW_ID']) 
                print ('Found New ID of ' +  File2Row['NEW_ID'] + ' at row ' + str(row)) 
                found = True 
                break 
            row += 1 
        if not found: 
            #need to write the entire File1Row to c3, with null value for non-matching values 
            print ('not found') 
 
 
    in_leg.close() 
    in_map.close() 
    out_res.close() 

请您参考如下方法:

希望其他人会根据您的纯 Python 代码给出示例,但只是为了向您展示如何在 pandas 中执行此操作,使用一些模拟数据:

import pandas as pd 
df_old = pd.read_csv("legacyFile.csv") 
df_new = pd.read_csv("NewMapping.csv") 
df_merged = df_old.merge(df_new, left_on="ID", right_on="LEGACY_ID", how="outer") 
df_merged.to_csv("combined.csv", index=False) 

此代码合并了一个 DataFrame(有点像表格或 Excel 工作表),看起来像

>>> df_old 
   ID col1 col2 
0   1    a    b 
1   2    c    d 
2   3    e    f 
3   4    g    h 

还有一个喜欢

>>> df_new 
   LEGACY_ID  NEW_ID  other_new_column 
0          1     100             12.34 
1          2     200             56.78 
2          4     400             90.12 

进入一个对象

>>> df_merged 
   ID col1 col2  LEGACY_ID  NEW_ID  other_new_column 
0   1    a    b          1     100             12.34 
1   2    c    d          2     200             56.78 
2   3    e    f        NaN     NaN               NaN 
3   4    g    h          4     400             90.12 

并将其写入 csv 文件。在这里,我保留了 NewMapping 文件中没有匹配项的第 3 行,但我们也可以轻松地只保留完全匹配的行。