How to Sort Pandas DataFrame by Index


Often you may want to sort a pandas DataFrame based on values in the index column.

The easiest way to do so is by using the sort_index() function, which uses the following basic syntax:

df.sort_index(axis=0, level=None, ascending=True, inplace=False, …)

where:

  • axis: The axis to sort on (0 = index, 1 = columns)
  • level: Index level to sort on
  • ascending: Whether or not to sort in ascending order
  • inplace: Whether or not to sort the index in-place

This function is particularly useful when the index values in a DataFrame are not simply listed from 1 to n and you’d like to sort the index by numerical values.

The following example shows how to use the sort_index() function to sort the index values of a pandas DataFrame in practice.

Example: How to Sort Pandas DataFrame by Index

Suppose we create the following pandas DataFrame that contains information about various basketball players:

import pandas as pd

#create DataFrame
df = pd.DataFrame({'team': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
                   'points': [18, 22, 19, 14, 14, 11, 40, 32],
                   'rebounds': [5, 7, 7, 9, 12, 9, 5, 17],
                   'minutes': [2.1, 4, 5.8, 9, 9.2, 3.5, 4.3, 15.4]},
                    index=[12, 8, 7, 9, 50, 3, 20, 21])

#view DataFrame
print(df)

   team  points  rebounds  minutes
12    A      18         5      2.1
8     A      22         7      4.0
7     A      19         7      5.8
9     B      14         9      9.0
50    B      14        12      9.2
3     B      11         9      3.5
20    C      40         5      4.3
21    C      32        17     15.4

The DataFrame contains four columns with various data about the individual basketball players while the very first column shown represents the index of the DataFrame.

Notice that the values in the index are not currently sorted.

To sort the rows of the DataFrame by the index values from smallest to largest, we can use the following syntax:

#sort DataFrame based on index values from smallest to largest
df.sort_index()

team	points	rebounds	minutes
3	B	11	9	3.5
7	A	19	7	5.8
8	A	22	7	4.0
9	B	14	9	9.0
12	A	18	5	2.1
20	C	40	5	4.3
21	C	32	17	15.4
50	B	14	12	9.2

Notice that the DataFrame is now sorted based on the values in the index column from smallest to largest.

For example, the row with an index value of 3 is shown first while the row with an index value of 50 (the largest index value) is shown last.

If you would instead like to sort the DataFrame based on index values from largest to smallest, you can specify ascending=False within the sort_index() function as follows:

#sort DataFrame based on index values from largest to smallest
df.sort_index(ascending=False)

team	points	rebounds	minutes
50	B	14	12	9.2
21	C	32	17	15.4
20	C	40	5	4.3
12	A	18	5	2.1
9	B	14	9	9.0
8	A	22	7	4.0
7	A	19	7	5.8
3	B	11	9	3.5

Notice that the DataFrame is now sorted based on the values in the index column from largest to smallest.

Note that we must use the argument inplace=True to sort the index values in the original DataFrame.

The following syntax shows how to do so:

#sort DataFrame based on index values in-place
df.sort_index(inplace=True)

#view original DataFrame
print(df)

   team  points  rebounds  minutes
3     B      11         9      3.5
7     A      19         7      5.8
8     A      22         7      4.0
9     B      14         9      9.0
12    A      18         5      2.1
20    C      40         5      4.3
21    C      32        17     15.4
50    B      14        12      9.2

We can see that the rows in the original DataFrame are now sorted based on index values from smallest to largest since we specified inplace=True.

Note: You can find the complete documentation for the pandas sort_index() function along with all optional arguments you can use with the function here.

Additional Resources

The following tutorials explain how to perform other common tasks in pandas:

Pandas: How to Sort by Date
Pandas: How to Sort Columns by Name
Pandas: How to Sort by Both Index and Column

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *