使用python查找CSV文件的每一列的最小值 [英] Finding the minimum of each column of a CSV file using python

查看:49
本文介绍了使用python查找CSV文件的每一列的最小值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,该程序查找CSV文件每一行的最小值,我现在想对每一列进行相同操作,但是我无法做到这一点.任何建议将不胜感激,谢谢.

I've created a program which finds the minimum of each row of a CSV file and I would now like to do the same for each column, however I have been unable to do so. Any advice would be greatly appreciated thank you.

       #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)

推荐答案

以下方法应该起作用:

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可能的替代版本:

Testing using Python 2.7. Below is also a possible alternative version for 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)

这篇关于使用python查找CSV文件的每一列的最小值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆