【问题标题】:How do I delete rows in one CSV based on rows in another CSV using specific columns to compare如何使用特定列进行比较,基于另一个 CSV 中的行删除一个 CSV 中的行
【发布时间】:2015-03-13 06:21:52
【问题描述】:

我有两个 CSV 文件,CSV1CSV2,包含多列和多行。其中一列的标题为ID

我想做的是检查CSV1 的行,如果CSV2ID 列中有IDCSV1 的行ID 匹配,那么我想保持这一行。如果没有匹配,那么我想从CSV1 中删除该行。

基本上CSV1 中的数据与我相关,但只有CSV2 中的人。两者之间的唯一联系是ID 列。所以我需要检查CSV1 中的所有行,看看ID 的行是否在CSV2 中的一行。

这是我目前所拥有的。

import csv
smarteeCSV = open("Smartee.csv", "r")
aeriesCSV = open("aeriesEditable.csv", "r+")

aeries = csv.reader(aeriesCSV, delimiter=',')##CSV1
smartee = csv.reader(smarteeCSV, delimiter=',')##CSV2    

for row in aeries:
    for item in smartee
    if row[1] != item[1]##indexes for the columns with the ids

我已经可以看出我的方向不对,所以有人可以帮忙吗?

【问题讨论】:

    标签: python loops csv compare


    【解决方案1】:

    您可以提取第二个文件中的所有 ID,并在每次检查第一个文件的其中一行时查找它们。

    例如:

    # extract ID column from CSV file 2 into a set
    Ids = { row[1] for row in smartee }
    
    # pick only rows whose ID is in Ids 
    filtered_rows = [item for item in aeries if item[1] in Ids] 
    

    【讨论】:

    • Ids 作为一个集合会更好,0(1) 而不是线性
    • 不用担心,小输入无关紧要,但处理大输入会更有效率。
    • 你们都是人中的神!工作完美,完全符合我的要求。你摇滚!!
    【解决方案2】:

    首先,读取 CSV2 来制作一组 ID:

    with open(CSV2) as f:
        r = csv.DictReader(f)
        theids = set(row['ID'] for row in r)
    

    然后,在读取 CSV1 时,只需检查 ID 是否在集合中:

    with open(CSV1) as f, open(CSV1 + '.new', 'w') as out:
        r = csv.DictReader(r)
        w = csv.DictWriter(out, r.fieldnames)
        for row in r:
            if row['ID'] in theids:
                w.writerow(row)
    

    这假设 CSV 文件适合基于 dict 的读/写(即第一行是列名列表),但如果列名也来自其他信息,则很容易调整。

    【讨论】:

      【解决方案3】:

      根据您计划对相关数据行执行的操作,您或许可以使用 Python 的内置 filter() 函数来执行您需要的操作:

      import csv
      
      # first get the ids    
      with open('Smartee.csv', 'rb') as smarteeCSV:  # CSV2
          ids = set(row['ID'] for row in csv.DictReader(smarteeCSV, delimiter=','))
      
      with open('aeriesEditable.csv', 'rb') as aeriesCSV:  # CSV1
          relevant = filter(lambda row: if row['ID'] in ids,
                              csv.DictReader(aeriesCSV, delimiter=','))
      
      # relevant will be a list containing the desired rows from CSV1
      

      如果您想迭代地处理行,对于第二部分,您可以使用for 循环来替代类似地调用itertools.ifilter() 函数的结果。

      【讨论】:

        猜你喜欢
        • 2021-09-26
        • 1970-01-01
        • 2013-04-12
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        • 2021-06-08
        • 2018-07-02
        相关资源
        最近更新 更多