Sort index in ascending order – Python Pandas


The sort_index() is used to sort index in ascending and descending order. If you won’t mention any parameter, then index sorts in ascending order.

At first, import the required library −

import pandas as pd

Create a new DataFrame. It has unsorted indexes −

dataFrame = pd.DataFrame([100, 150, 200, 250, 250, 500],index=[4, 8, 2, 9, 15, 11],columns=['Col1'])

Sort the indexes −

dataFrame.sort_index()

Example

Following is the code −

import pandas as pd

dataFrame = pd.DataFrame([100, 150, 200, 250, 250, 500],index=[4, 8, 2, 9, 15, 11],columns=['Col1'])

print"DataFrame...\n",dataFrame

print"\nSort index...\n",dataFrame.sort_index()

Output

This will produce the following output −

DataFrame...
   Col1
4   100
8   150
2   200
9   250
15  250
11  500

Sort index...
   Col1
2   200
4   100
8   150
9   250
11  500
15  250

Updated on: 21-Sep-2021

640 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements