查找并显示具有近似闭合项的行

2024-05-07 23:51:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个代码来查找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和chan2的值,它们之间的距离在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]

但我不知道从这里走到哪里,我不知道我是否应该使用“如果”状态,或者是否有任何其他方式来获得我需要的信息。最终,我希望程序打印3件事:

非常接近(close by<=1.0)找到Chan1和Chan2中的值,即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])

Tags: csvinfromimporthomefordatanp
2条回答

您可以使用减法和绝对值函数确定两个值之间的距离是否在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]))

我想我们可以用标准库函数来解决你的问题

只是友好的提示:

这三条线

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)

相关问题 更多 >