【问题标题】:CSV compare column values pythonCSV比较列值python
【发布时间】:2015-09-28 06:01:24
【问题描述】:

我有 2 个 csv 文件分别为 csv1csv2

csv1

1,9,10
2,10,11
3,11,10

csv2

2,b
1,a
3,c

我想检查 csv1 第一列到 csv2 第一列的每个值,如果有匹配,则 csv2 第二列的另一个值 附加到 csv1。 我的最终输出是:

1,9,10,a
2,10,11,b
3,11,10,c

【问题讨论】:

标签: python csv


【解决方案1】:

使用 python 的 CSV 模块读取文件。 https://docs.python.org/2/library/csv.html

使用 for 循环比较两个文件并将结果写入 CSV。

【讨论】:

    【解决方案2】:

    算法

    1. 使用csv模块读写csv文件。
    2. 创建 csv 文件 2 的字典结构
    3. 以写入模式打开新文件。
    4. 以读取模式打开 csv 文件 1。
    5. 迭代 csv 文件 1 中的每一行。
    6. 检查该行中的第一项是否存在于字典中(第 2 点)。
    7. 如果 6 为真,则将字典中的值附加到当前行。
    8. 将行写入文件。(第 3 点)。

    代码

    import csv
    # Create Dictionary structure of csv file 2
    with open("/home/vivek/2.csv", "rb") as fp:
        root = csv.reader(fp,)
        root2 = {}
        for i in root:
            root2[i[0]] = i[1]
    
    print "Debug 1: Dictionary of file 2:", root2
    
    with open("/home/vivek/output.csv", "wb") as fp:
        with open("/home/vivek/1.csv", "rb") as fp1:
            output = csv.writer(fp, delimiter=",")
            root = csv.reader(fp1,)
            for i in root:
                #Check first item from the row is present in dictionary.  
                if i[0] in root2:
                    i.append(root2[i[0]])
                output.writerow(i)
    

    列表追加与连接:

    >>> import timeit
    >>> def addtest():
    ...   l = []
    ...   for i in range(1000): 
    ...       l +[i]
    ... 
    >>> def appendtest():
    ...   l = []
    ...   for i in range(1000): 
    ...       l.append(i)
    ... 
    >>> print "Time 1:", timeit.timeit('appendtest()', 'from __main__ import appendtest')
    Time 1: 110.55152607
    >>> print "Time 1:", timeit.timeit('addtest()', 'from __main__ import addtest')
    Time 1: 265.882155895
    

    【讨论】:

      【解决方案3】:

      下面应该做你需要的,它利用了 Python 的 csv 模块。它首先将整个csv2 读入一个字典,然后可以在读取csv1 时查看该键是否存在:

      import csv  
      
      d_csv2 = {}
      
      with open('2.csv', 'r') as f_csv2:
          csv_2 = csv.reader(f_csv2)
          for cols in csv_2:
              d_csv2[cols[0]] = cols[1]
      
      with open('1.csv', 'r') as f_csv1, open('output.csv', 'wb') as f_output:
          csv_1 = csv.reader(f_csv1)
          csv_output = csv.writer(f_output)
      
          for cols in csv_1:
              if cols[0] in d_csv2:
                  csv_output.writerow(cols + [d_csv2[cols[0]]])
      

      它会创建以下output.csv 文件:

      1,9,10,a
      2,10,11,b
      3,11,10,c
      

      【讨论】:

      • 是的,我们可以在一行中编写with 语句,列表中的concatenation 会比append 花费更多时间
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2018-05-10
      • 1970-01-01
      相关资源
      最近更新 更多