在python中的csv行中查找相同的值

时间:2014-10-06 06:43:16

标签: python csv

我有一个代码,用于查找csv文件中的数字,这些数字在同一行中彼此相差1.0个小数位。虽然,当我运行它时,它会打印所有内容。不仅仅是具有我想要的条件的行,即第2列和第3列的值在彼此的1.0之内。我想运行代码并让它显示,第一列(记录时间或列号更好),第二列和第三列,因为它们应该在1.0之内。这就是数据文件的样子:

Time    Chan1       Chan2
04:07.0 52.31515503 16.49450684
04:07.1 23.55230713 62.48802185
04:08.0 46.06217957 24.94955444
04:08.0 41.72077942 31.32516479
04:08.0 19.80723572 25.73182678

这是我的代码:

import numpy as np
from matplotlib import *
from pylab import *

filename = raw_input("Enter file name: ") + '.csv'
filepath = '/home/david/Desktop/' + filename


data = np.genfromtxt(filepath, delimiter=',', dtype=float)



first=[row[0] for row in data]
rownum1=[row[1] for row in data]
rownum2=[row[2] for row in data]



for row in data:
    if ((abs(row[1]-row[2]) <= 1.0)):
        print("The values in row 0 are 1 and 2, are within 1.0 of each other.", first, rownum1, rownum2)

这是我的输出:

26.3460998535, 44.587371826199998, 42.610519409200002, 24.7272491455, 89.397918701199998, 25.479614257800002, 30.991180419900001, 25.676086425800001

但我希望这是一个输出:

4:09.0, 23.456, 22.5

1 个答案:

答案 0 :(得分:1)

你可以这样做:

data = np.genfromtxt(filepath, names=True, dtype=None)
idx = np.abs(data['Chan1'] - data['Chan2'])<1
print data[idx]