I have a csv file with the data like input.csv:
1285,375,2.0,3.5,2473
260,380,2.0,3.5,3780
2205,35,1.0,1.75,4829
245,25,1.0,1.75,5632
570,1520,1.0,1.75,8240
465,35,1.0,1.75,10287
3325,35,1.0,0.75,20788
2480,75,1.0,1.75,23589
0,15,4.0,7.0,48424
When using the operator.itemgetter
:
import csv
import operator
inputfile="input.csv"
with open(inputfile, newline='') as csvfile:
next(csvfile)
outcsv = csv.reader(csvfile, delimiter=',', quotechar='|')
sorted_csv = sorted(outcsv, key = operator.itemgetter(0))
for eachline in sorted_csv:
print(eachline)
the output I get is alphabetically sorted in the first column:
['0', '15', '4.0', '7.0', '48424']
['1285', '375', '2.0', '3.5', '2473']
['2205', '35', '1.0', '1.75', '4829']
['245', '25', '1.0', '1.75', '5632']
['2480', '75', '1.0', '1.75', '23589']
['260', '380', '2.0', '3.5', '3780']
['3325', '35', '1.0', '0.75', '20788']
['465', '35', '1.0', '1.75', '10287']
['570', '1520', '1.0', '1.75', '8240']
to sort the CSV file on the first column and ensure that the sorting is done using the numeric values instead. I did the following:
import csv
inputfile="input.csv"
with open(inputfile, newline='') as csvfile:
next(csvfile)
outcsv = csv.reader(csvfile, delimiter=',', quotechar='|')
sorted_csv = sorted(outcsv, key = lambda start_time: int(start_time[0]))
for eachline in sorted_csv:
print(eachline)
Output is as expected.
['0', '15', '4.0', '7.0', '48424']
['245', '25', '1.0', '1.75', '5632']
['260', '380', '2.0', '3.5', '3780']
['465', '35', '1.0', '1.75', '10287']
['570', '1520', '1.0', '1.75', '8240']
['1285', '375', '2.0', '3.5', '2473']
['2205', '35', '1.0', '1.75', '4829']
['2480', '75', '1.0', '1.75', '23589']
['3325', '35', '1.0', '0.75', '20788']
To sort on any other column by magnitude (value of the number) simply replace the column number in the line:
sorted_csv = sorted(outcsv, key = lambda start_time: int(start_time[0]))