How to sort an index with Pandas
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
In order to correctly plot the majority of your DataFrames you will eventually need to sort the index.
In Python there is a simple method to perform such operation.
In Pandas the method is called .sort_index().
It will be important to correctly define the data types of the index column we want to sort.
So that Python will know how to correctly sort this index.
Sorting a timestamp index
Timestamp might come as the primer example of such index sorting.
It is crucial to correctly define its data type.
Let me show you an example using Bitcoin prices fetched from coingecko.com free api.
We now use the .sort_index() method to order the DataFrame by ascending index.
If we want the DataFrame to be in descending order. (Most recent first, so the biggest value first)
Sorting an int64 index
In order to sort an int64 index, we can reuse the method used in the example above.
your_dataframe = your_dataframe.sort_index() # By ascending order
your_dataframe = your_dataframe.sort_index(ascending=False) # By descending order
Sorting a string index
Sorting index will use the same method than the two other examples.
Lets take an example of a DataFrame composed of names and uuids.
# We setup the dataframe
df = pd.DataFrame({"uuid" : ['ba7f584c-b87d-47c2-8edb-529e64cd8912',
'6918a068-506b-4fa0-b475-db6e308ec4c3',
'19f7e905-8a50-43f6-a23e-3ef24d767a88',
'74514e08-541c-4aeb-9966-3f878c0e5652',
'859c289f-0c13-466f-a942-ae50bd2df143',
'453cc9e0-0f62-4d1b-88ef-85bafa5bc55b'],
"names": ["Bob", "Jamie", "Jonas", "Caroline","Vanessa", "Aline"]})
# We set the uuid column as index
df = df.set_index("uuid", drop=True)
Or in descending order
Here you are ! You know now how to sort an index with Pandas !
More on DataFrames
If you want to know more about DataFrame and Pandas. Check out the other articles I wrote on the topic, just here :
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months 🚀
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons – Approach used by real data scientist. Not bookworms. 📚