Pandas DataFrame - Sort by Index
Pandas DataFrame - Sort by Index
To sort a Pandas DataFrame by index, you can use DataFrame.sort_index() method.
To specify whether the method has to sort the DataFrame in ascending or descending order of index, you can set the named boolean argument ascending
to True or False respectively.
When the index is sorted, respective rows are rearranged.
Examples
1. Sort DataFrame by index in ascending order
In this example, we shall create a dataframe with some rows and index with an array of numbers. We shall sort the rows of this dataframe, so that the index shall be in ascending order.
To sort the index in ascending order, we call sort_index() method with the argument ascending=True
as shown in the following Python program. Or you may ignore the ascending parameter, since the default value for argument ascending
is True
.
Python Program
import pandas as pd
#create a dataframe
df_1 = pd.DataFrame(
[['Arjun', 70, 86],
['Kiku', 80, 76],
['Mama', 99, 99],
['Lini', 79, 92]],
index = [2, 1, 6, 5],
columns=['name', 'aptitude', 'cooking'])
print(df_1)
#sort dataframe by index in ascending order
df_1 = df_1.sort_index(ascending=True)
print('\nDataFrame after sorting by index\n')
print(df_1)
Output
Run the above program. We have printed the original DataFrame to the console, followed by sorted DataFrame.
name aptitude cooking
2 Arjun 70 86
1 Kiku 80 76
6 Mama 99 99
5 Lini 79 92
DataFrame after sorting by index
name aptitude cooking
1 Kiku 80 76
2 Arjun 70 86
5 Lini 79 92
6 Mama 99 99
2. Sort DataFrame by index in descending order
In this example, we shall sort the DataFrame based on the descending order of index. For that, we shall pass ascending=False
to the sort_index() method.
Python Program
import pandas as pd
#create a dataframe
df_1 = pd.DataFrame(
[['Arjun', 70, 86],
['Kiku', 80, 76],
['Mama', 99, 99],
['Lini', 79, 92]],
index = [2, 1, 6, 5],
columns=['name', 'aptitude', 'cooking'])
print(df_1)
#sort dataframe by index in descending order
df_1 = df_1.sort_index(ascending=False)
print('\nDataFrame after sorting by index\n')
print(df_1)
Output
Run the program. The sorted dataframe has index [6 5 5 1]
in descending order.
name aptitude cooking
2 Arjun 70 86
1 Kiku 80 76
6 Mama 99 99
5 Lini 79 92
DataFrame after sorting by index
name aptitude cooking
6 Mama 99 99
5 Lini 79 92
2 Arjun 70 86
1 Kiku 80 76
Summary
In this tutorial of Python Examples, we learned how to sort a Pandas DataFrame by index in ascending and descending orders.