如何在csv文件中查找包含行最高值的列名

时间:2019-04-20 23:27:15

标签: python

我试图在遍历每一行并从该行获取最高值后获取列标题,我该怎么做?

with open(filePath) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:        
            euro = int(row['Euro'])       
            usd = int(row['Usd']) 
            pound = int(row['Pound'])
            yuan= int(row['Yuan'])
            max_curr = max(euro,usd,pound,yuan)

Example rows

例如。对于第一行数据,我想打印标题“ Euro”,因为该行中的最大值是99

对于第二行,我要打印标题“ Usd”,因为该行中的最大值是99

2 个答案:

答案 0 :(得分:2)

key函数中使用max()参数:

import csv
from collections import OrderedDict

with open(filePath) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        # converting the row values to integers.
        row = OrderedDict((k, int(v)) for k, v in row.items())
        # getting the column name of the max value
        max_curr = max(row, key=row.get)
        print(max_curr)

答案 1 :(得分:0)

这是我的解决方法:

import csv

with open("/tmp/data.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        max = -1
        for name in reader.fieldnames:
            v = int(row[name])
            if v > max:
                max = v
                maxname = name
        print(str(max) + ' ' + maxname)

输入:

Euro,Usd,Pound,Yuan
1,2,3,4
7,2,14,8
9,23,7,12
1,2,3,4

它产生:

4 Yuan
14 Pound
23 Usd
4 Yuan

当然,如果您不想这样做,就不必打印该值。