gpt4 book ai didi

python - 使用python查找CSV文件每一列的最小值

转载 作者:太空宇宙 更新时间:2023-11-03 15:07:08 24 4
gpt4 key购买 nike

我创建了一个程序来查找 CSV 文件每一行的最小值,现在我想对每一列执行相同的操作,但是我一直无法这样做。如有任何建议,我们将不胜感激。

       #Import and convert csv
import csv
data = []
with open(file,"r") as f:
reader = csv.reader(f, delimiter=',')
#make sure csv uses "." not "," !!!!!
nump = 0
for row in reader:
floatrow = []
for val in row:
floatrow.append(float(val))
nump += len(floatrow)
data.append(floatrow)

#Calculates minimum of each row, minimum and sum of row
minrr = []
sum1 = 0.0
for row in data:
list2 = (min (filter(None, row)))
minrr.append(list2)
sum1 += sum(row)

最佳答案

您可以只使用 python 内置命令和通过压缩所有行实现的转置,如下所示:

import csv
a = []
with open('path/to/file.csv',"r") as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
#turn all input to floats
row = map (float, row)
#append the entire row to create list of lists
a.append(row)
# Transpose a into b
b = zip (*a)
# Now min of row will be min of col in a
for line in b:
print min(line)

关于python - 使用python查找CSV文件每一列的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378137/

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