查找并显示具有近似条目的行

时间:2014-10-06 05:06:31

标签: python csv

我正在编写一个代码来查找不重复的内容,而是编写csv文件中的近似值。 我希望能够找到同一行中差异不超过1.0的所有值 csv文件如下所示:

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

我想找到Chan1和Chan 2的值,它们彼此相差1.0。 这就是我的全部:

import nump as np
from matplotlib import *
from pylab import *
filename = raw_input("Enter file name: ")+'.csv'
filepath = 'home/home/david/Desktop/'+filename
col1=[row[2] for row in data]
col2=[row[3] for row in data]

但是我不知道从哪里开始,我不知道我是否应该使用'if'状态,或者是否有其他方式来获取我需要的信息。我最终希望程序打印3件事:

找到Chan1和Chan2中非常接近(接近< = 1.0)值的行,Chan1和Chan2。

以下是我刚刚编辑的内容:

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]

#if (abs(rownum1-rownum2)<=1):
#       print( first, rownum1, rownum2)

count=0
for row in data:
     count++
     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.', format(count, row[1], row[2])

2 个答案:

答案 0 :(得分:2)

我认为我们可以使用标准库函数解决您的问题。

友好的说明:

这3行

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

将执行3 x 10.000循环,最好在每行读取数据时进行拆分。

请按照@ 0O0O0O0请求复制粘贴错误

try:
    text_file = open("list_number.txt", "r") #File contain your 5 line data, with header removed

    try:
        count = 0
        for row in text_file:
            col = row.split() # switch to row.split(',') if you're using coma delimiter
            count+=1
            if abs(float(col[1]) - float(col[2])) <= 10: # Change to 1
                #print('The values in row %s are %s and %s, are within 10.0 of each other.' % (count, col[1], col[2]))
                print('The values in row {0} are {1} and {2}, are within 10.0 of each other.'.format(count, col[1], col[2]))
    finally:        
        text_file.close()

except IOError as e:
    print("Unable to open file : ", e)

答案 1 :(得分:1)

您可以使用减法和绝对值函数确定这两个值是否在1.0之内:

count = 0
for row in data:
    count++
    if (abs(row[2] - row[3]) <= 1.0):
        print('The values in row {0} are {1} and {2}, and are within 1.0 of each other.'.format(count, row[2], row[3]))