首页 > 解决方案 > 如何在csv文件中查找包含行的最大值的列名

问题描述

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

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)

示例行

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

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

标签: python

解决方案


在函数中使用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)

推荐阅读