简体   繁体   中英

How to find column name that contains the highest value of a row in a csv file

I'm trying to get the column header after going through each row and getting the highest value from that row, how do i do it?

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)

示例行

Eg. For the first row of data, i want to print the header 'Euro' as 99 is the largest value in that row

And for the second row, i want to print the header 'Usd' as 99 is the largest value in that row

Use the key parameter in max() function:

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)

Here's my solution:

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)

For input:

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

It produces:

4 Yuan
14 Pound
23 Usd
4 Yuan

Of course, you don't have to print the value if you don't want to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM