【发布时间】:2015-10-20 17:35:06
【问题描述】:
我是 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
更新
预期输出:
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 访问这些文件。如果您有任何想法,请告诉我。谢谢。
【问题讨论】:
-
你的预期输出是什么?
-
@AerofoilKite 我更新了帖子。
-
这些 csv 文件中是否有可能有一个看似空的行或一行没有足够的字段?这就是错误消息所暗示的。如果您不知道,您应该考虑为这两个文件添加一个链接,以便其他人可以检查它们。
-
您确定不要插入时间吗?例如,如果最接近的匹配是
cassandra,01:01:00.000123和cpu,01:01:00.000175,您真的不想输出任何内容吗? -
使用
bisect在排序后的数组中找到最近的匹配;确定缺失数据的启发式方法(例如 >1s 太远了)。