How to sort an index with Pandas

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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.

df_btc_prices = pd.read_json("https://api.coingecko.com/api/v3/coins/bitcoin/ohlc?vs_currency=usd&days=14")
We fetch our DataFrame containing bitcoin prices
# We change the column names to something usable
df_btc_prices.columns = ["datetime","open", "high", "low", "close"]

# We set the index to be our datetime column
df_btc_prices = df_btc_prices.set_index("datetime",drop=True)

# As our datetime column is still in int64 format we transform
# it using the .to_datetime function
df_btc_prices.index = pd.to_datetime(df_btc_prices.index, unit='ms')
Basic cleaning for the example DataFrame

We now use the .sort_index() method to order the DataFrame by ascending index.

df_btc_prices.sort_index()
The method that will sort by ascending order


If we want the DataFrame to be in descending order. (Most recent first, so the biggest value first)

df_btc_prices.sort_index(ascending=False)
The method that will sort by descending order

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)
df = df.sort_index()
Ascending order

Or in descending order

df = df.sort_index(ascending=False)
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 :

Pandas - The Python You Need
We gathered the only Python essentials that you will probably ever need.
7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. 📚

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.