我是python的初学者,我正在尝试比较两个csv文件中的两个字段(时间戳),如果匹配则将它们合并到第三个文件中 . 输入文件如下:
文件1:
name,time,operation
Cassandra,2015-10-06T15:07:22.333662984Z,INSERT
Cassandra,2015-10-06T15:07:24.334536781Z,INSERT
Cassandra,2015-10-06T15:07:27.339662984Z,READ
文件2:
name,time,host,instance,type,type_instance,value
cpu_value,2015-10-06T15:07:22.333662984Z,vm1-VirtualBox,0,cpu,user,24874
cpu_value,2015-10-06T15:07:24.334536781Z,vm1-VirtualBox,0,cpu,nice,592
cpu_value,2015-10-06T15:07:27.339662984Z,vm1-VirtualBox,0,cpu,system,2932
这是我到目前为止所尝试的:
import csv
with open('f1.csv', 'rb') as f1, open ('f2.csv', 'rb') as f2:
next(f1) #skip line 1
next(f2) #skip line 1
reader1 = csv.reader(f1)
reader2 = csv.reader(f2)
for row1 in reader1:
for row2 in reader2:
if row1[1] == row2[1]:
data = [row1[0],row2[0]]
print data
然后,我收到了这个错误:
['cpu_value', 'Cassandra']
Traceback (most recent call last):
File "merger.py", line 10, in <module>
if row1[1] == row2[1]:
IndexError: list index out of range
Update
预期产量:
Cassandra,2015-10-06T15:07:22.333662984Z,INSERT,cpu_value,vm1-VirtualBox,0,cpu,user,24874
Cassandra,2015-10-06T15:07:24.334536781Z,INSERT,cpu_value,vm1-VirtualBox,0,cpu,nice,592
Cassandra,2015-10-06T15:07:27.339662984Z,READ,cpu_value,vm1-VirtualBox,0,cpu,nice,592
您可以通过此link访问这些文件 . 如果您有任何想法,请告诉我 . 谢谢 .
3 回答
如果我们可以假设所有时间戳都是唯一的并且它们将完全匹配(也就是说,不需要插值),那么我们可以通过将第一个文件读入字典开始,其中键是时间戳,值是CSV行 .
然后,我们读取第二个文件,并为每个CSV行查找字典 . 如果有匹配的行,我们可以打印,或存储,或其他任何东西 . 此外,我们使用
pop
删除匹配的行,以便我们可以轻松找到最终的不匹配行!以下代码应为2 * 3行的测试数据提供所需的输出 .
你也可以使用pandas DataFrame:pandas package
输出:
更多信息:http://pandas.pydata.org/pandas-docs/stable/merging.html
输出:
您也可以尝试pandas DataFrame:https://stackoverflow.com/a/33244071/1924666