gpt4 book ai didi

python - 在 CSV 中查找最小值并在 Python 中打印包含它的每一行

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:49 25 4
gpt4 key购买 nike

非常感谢您的帮助。我正在尝试编写一个脚本,它将遍历一个 csv 文件文件夹,在第二列中找到最小值并打印包含它的每一行。脚本查看的 csv 文件如下所示:

TPN,12010,on this date,25,0.00005047619239909304377497309619
TPN,12011,on this date,23,0.00003797836224092152019127884704
TPN,12012,on this date,78,0.0001130474103447076420049393022
TPN,12020,on this date,27,0.00005671375308512314236202279053
TPN,12021,on this date,60,0.00009856619048244864701475864425

脚本如下所示:

import csv
import os

folder = '/Users/Documents/Senior/Thesis/Python/TextAnalysis/datedmatchedngrams2/'

identity = []
for filename in os.listdir (folder):
with open(filename, 'rb') as inf:
incsv = csv.reader(inf)
column = 1
datatype = int
data = (datatype(row[column]) for row in incsv)
least_value = min(data)
print least_value
for row in incsv:
if least_value in column[1]:
identity.append(row)
else:
print "No match"
print identity

我得到的错误是:

  File "findfirsttrigram.py", line 12, in <module>
identity.append("a")
NameError: name 'identity' is not defined

我也试过这样做:

import csv
import os

folder = '/Users/Documents/Senior/Thesis/Python/TextAnalysis/datedmatchedngrams2/'

for filename in os.listdir (folder):
with open(filename, 'rb') as inf:
incsv = csv.reader(inf)
column = 1
datatype = int
data = (datatype(row[column]) for row in incsv)
least_value = min(data)
print least_value
for row in incsv:
if least_value in row:
print row
else:
print "No match"

但这也没有用。它没有给我一个错误,但它也没有打印“不匹配”,所以我不知道从哪里开始。请帮忙!!

最佳答案

你可以这样做:

import csv

# for each_file in os.listdir (folder):
with open(each_file) as f:
m=min(int(line[1]) for line in csv.reader(f))
f.seek(0)
for line in csv.reader(f):
if int(line[1])==m:
print line

关于python - 在 CSV 中查找最小值并在 Python 中打印包含它的每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27369945/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com