How to sort an index of numbers with Pandas in Python

1 min

In order to sort an index made of numbers, we can use the DataFrame.sort_index() method like in the example below.

# We import pandas
import pandas as pd

# We generate our sample dataset
df = pd.DataFrame(index=sorted(list(range(10)), reverse=True),
				  data={"col1":range(10)})

print(df)

# By ascending order
print(df.sort_index()) 

# By descending order
print(df.sort_index(ascending=False))

Here you are! You now know how to sort an index of numbers with Pandas in Python!

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.