user17839607
user17839607

Reputation:

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

Upvotes: 1

Views: 2876

Answers (4)

user7864386
user7864386

Reputation:

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.

Upvotes: 1

Stef
Stef

Reputation: 15525

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

Upvotes: 1

SEUNGFWANI
SEUNGFWANI

Reputation: 160

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')

Upvotes: 1

Nabil
Nabil

Reputation: 1278

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

Upvotes: 0

Related Questions