How to sort an index with Pandas

2 min

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 free api.

df_btc_prices = pd.read_json("")
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.

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)

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',
                   "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.