Reputation: 21
Is it possible to sort a csv file in python by an average, alphabetical order etc. Right now I have a simple print row code and am wondering if it's possible to sort the data. (Name, class and score) It's for a task so I can't display my code here, so all answers are appreciated.
Upvotes: 2
Views: 1072
Reputation: 165
If you are looking for sorting of a csv file based on columns, here is a quick solution:
import csv
import operator
# Sort based on 3 column, iteration starts at zero (0)
r=csv.reader(open("1.csv"), delimiter=",")
print("Sorted based on 3rd column")
print(sorted(r, key=operator.itemgetter(2), reverse=True))
# Sort based on 2 column, iteration starts at zero (0)
r=csv.reader(open("1.csv"), delimiter=",")
print("\nSorted based on 2nd column")
print(sorted(r, key=operator.itemgetter(1), reverse=True))
Suppose your csv is as mentioned below
$> cat 1.csv
1,a,32,hello
2,x,33,xello
3,h,23,belo
4,z,3,elo
Then when you run the above code:
$> python ./sort.py
Sorted based on 3rd column
[['2', 'x', '33', 'xello'], ['1', 'a', '32', 'hello'], ['4', 'z', '3', 'elo'], ['3', 'h', '23', 'belo']]
Sorted based on 2nd column
[['4', 'z', '3', 'elo'], ['2', 'x', '33', 'xello'], ['3', 'h', '23', 'belo'], ['1', 'a', '32', 'hello']]
Is this what you were looking for?
Upvotes: 1