I have imported a CSV file to a list in python containing animal data with the following columns:
Sanctuary Identification,Type,Breed,Vaccinated,Neutered
P23533,Cat,Persian,Yes,Yes
P43533,Dog,Poodle,Yes,No
P18754,Dog...
The data appears in the following format:
[[P23533,Cat,Persian,Yes,Yes],[P43533,Dog,Poodle,Yes,No],[P18754,Dog...]]
I would like to sort the list in ascending order of their Sanctuary Indentifaction, ie:
P1111, Cat, ..
P2222 Dog, ..
P3333.. etc
I cannot use any build in libraries, can anyone suggest how I might go about this?
You could sort the nested list using sorted
built-in function, then pass in the first column as the key to be sorted. Below is the example.
In [1]: my_list = [["P23533","Cat","Persian","Yes","Yes"],["P43533","Dog","Poodle","Yes","No"], ["P1111","Asd","Test","
...: Yes","Yes"]]
In [2]: sorted(my_list, key=lambda x: x[0])
Out[2]:
[['P1111', 'Asd', 'Test', 'Yes', 'Yes'],
['P23533', 'Cat', 'Persian', 'Yes', 'Yes'],
['P43533', 'Dog', 'Poodle', 'Yes', 'No']]
Alternatively, you can use pandas.read_csv
to load your csv into DataFrame
object, then use sort_values
function:
In [10]: df.sort_values(["SanctuaryID"]).reset_index(drop=True)
Out[10]:
SanctuaryID Animal Type Col4 Col5
0 P1111 Asd Test Yes Yes
1 P23533 Cat Persian Yes Yes
2 P43533 Dog Poodle Yes No
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.