简体   繁体   中英

How do I sort a csv file so that my columns are in descending order?

I'm trying to sort my CSV file so that the teams with the most gold, silver and bronze medals are at the top of the list and those with the least are at the bottom.

def rank_team(file_name):
import csv

file = open('medal.csv')
for line in file:
    print(line)

pass

rank_team('medal.csv')

This is the code that I have now. Just wondering how I would sort it all.

This is the CSV that I'm using. CSV used to sort

Using the csv.reader and csv.writer functions, as well as sorted with a tuple key:

import csv

with open('medal.csv', 'r') as in_file:
    in_reader = csv.reader(in_file)
    header = next(in_reader)
    data = sorted(in_reader, key=lambda row: tuple(int(x) for x in row[1:]), reverse=True)

with open('sorted_medal.csv', 'w', newline='') as out_file:
    out_writer = csv.writer(out_file)
    out_writer.writerow(header)
    out_writer.writerows(data)

Result:

# Input: medal.csv
team,gold,silver,bronze
t1,17,12,38
t2,8,7,29
t3,17,11,39
t4,17,12,37
t5,8,9,30

# Output: sorted_medal.csv
team,gold,silver,bronze
t1,17,12,38
t4,17,12,37
t3,17,11,39
t5,8,9,30
t2,8,7,29

You can use pandas for this. Read the csv as a pd.DataFrame and use sort_values method:

import pandas as pd
df = pd.read_csv('medal.csv')
df = df.sort_values(by=['Gold','Silver','Bronze'], ascending=False)

Note: What you describe is descending order.

Here a link that might help you. Change the 3 by 0 since you want to use the first column.

you can use sorted function with key condition.

if you want to sort ascending [Gold,Silver,Bronze], then this code will help you.

import csv


def rank_team(file_name):
    with open('medal.csv') as f:
        reader = csv.reader(f)
        header = next(reader)
        data = [row for row in reader]
    print(header)
    print(sorted(data, key=lambda x: (x[1], x[2], x[3])))


rank_team('medal.csv')

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