【问题标题】:Python CSV File Row ComparePython CSV 文件行比较
【发布时间】:2021-05-26 05:36:14
【问题描述】:

我有一个 csv 文件,其中每一行如下所示:

OrderedDict([('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3'), ('key4', 'value4'), ('key5', 'value5')]) 

我想比较相邻行上的两个键以查找匹配项并将这些行(字典)存储到列表中。

#if (key1 and key2) in row[i+1] == row[i]
            #append row[i] and row[i+1] to a new match list; becomes a list of dicts
#else go to next row

我很难理解如何在 python 中引用一行。我知道 enumerate 会给我每行的索引号,但我不清楚如何或是否可以将其用作参考。 Itertools 似乎会有所帮助,但不知道如何应用它。

【问题讨论】:

    标签: python list csv dictionary compare


    【解决方案1】:

    我假设你的 csv 文件就像你提到的那样

    key1, key2 ,...
    val11, val12 ,..
    val21, val22 ,..
    

    现在编码如果

      with open('test.csv','r') as f:
            csv_lst = list(csv.DictReader(f))  # if your csv is large than this can be problem
    
            for first_row,next_row in zip(csv_lst,csv_lst[1:]):
                print("Now you have both row with dictionary you can apply your logic ")
    

    并行迭代的python方法是使用zip,所以我转换了列表中的所有csv数据,然后zip(csv_list, csv_list[1:])第一个参数意味着从0开始的csc_list,其他参数意味着从1开始csv_list所以你将拥有@987654326 @list 的迭代。

    【讨论】:

    • 我还没有完成测试,但是这种方法看起来可行。也谢谢你的解释。光看代码我不会明白它是如何工作的。
    • 我完成了测试,这种方法有效。
    • 我发现 f, s 已经是 dicts 所以语句 first_row = dict(f) 和 next_row = dict(s) 是不需要的。 s和f可以直接使用。
    • @Duncan 你是对的,所以我已经编辑了
    【解决方案2】:

    根据定义,字典中的键是唯一的。因此,比较 2 个“行”的键不太可能起作用。此解决方案使用 pandas。

    假设“Sample_data.csv”包含这些行(以“键”作为第一列):

    键、值

    A, 1

    B,2

    C, 3

    C,33

    D,4

    E,5

    E,55

    import pandas as pd
    data1 = pd.read_table('sample_data.csv', sep=',')  # imports data into dataframe
    outdata = (data1[['keys']]==data1[['keys']].shift()).any(axis=1)   # bool of rows to capture
    data2 = data1.loc[outdata | outdata.shift(-1),]   # captured rows and one before it, includes all columns
    data2
    

    输出:

    index keys values
    2 C 3
    3 C 33
    5 E 5
    6 E 55

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-05
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多