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

时间:2015-07-13 07:59:02

标签: python csv

我创建了一个程序,它找到了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)

3 个答案:

答案 0 :(得分:2)

你可以只使用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)

答案 1 :(得分:1)

我建议使用np.loadtxt将文件读取为header("Access-Control-Allow-Origin: *"); 并使用给定的轴执行np.min

ndarray

这里有一点说明:

import numpy as np

arr = np.loadtxt('your_file.csv')
# for each column
minima_c = np.min(arr, axis=0)

# for each row
minima_r = np.min(arr, axis=1)

答案 2 :(得分:1)

以下内容应该有效:

with open("data.csv", "r") as f_input:
    lmin_col = []
    lmin_row = []

    for row in csv.reader(f_input):
        row = map(float, row)
        lmin_row.append(min(row))

        if lmin_col:
            lmin_col = map(min, lmin_col, row)
        else:
            lmin_col = row

    print "Min per row:", lmin_row
    print "Min per col:", lmin_col

输入以下内容:

10.1, 15.6, 12.3, 13.2, 17.0
2.1,  5.3,  7.0,  11.4, 5.5
12.1, 7.0,  9.3,  28.7, 1.0

它提供以下输出:

Min per row: [10.1, 2.1, 1.0]
Min per col: [2.1, 5.3, 7.0, 11.4, 1.0]

使用Python 2.7进行测试。下面是Python 3.0的可能替代版本:

with open("data.csv", "r") as f_input:
    lmin_col = []
    lmin_row = []

    for row in csv.reader(f_input):
        row = [float(col) for col in row]
        lmin_row.append(min(row))

        if lmin_col:
            lmin_col = [min(x,y) for x,y in zip(lmin_col, row)]
        else:
            lmin_col = row

    print("Min per row:", lmin_row)
    print("Min per col:", lmin_col)