[英]How to find column name that contains the highest value of a row in a csv file
我试图在遍历每一行并从该行获取最高值后获取列标题,我该怎么做?
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 是该行中的最大值
使用max()
函数中的key
参数:
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)
这是我的解决方案:
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
当然,如果您不想,您不必打印该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.