繁体   English   中英

CSV比较列值python

[英]CSV compare column values python

我有2个csv文件分别为csv1csv2

csv1

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

csv2

2,b
1,a
3,c

我要检查CSV2的第一列csv1的第一列的每个值,如果有匹配CSV2的第二列的其他值追加到csv1。 我的最终输出将是:

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

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

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

算法

  1. 使用csv模块读取和写入csv文件。
  2. 创建csv文件2的字典结构
  3. 在写入模式下打开新文件。
  4. 在读取模式下打开csv文件1。
  5. 迭代csv文件1中的每一行。
  6. 检查该行中的第一项是否存在于字典中(第2点)。
  7. 如果6为true,则将值从字典追加到当前行。
  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

以下应该做您需要的事情,它利用了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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM