How to sort the dataframe in python pandas by index in terms of ascending and descending order with an example for each using sort_index() method, our focus on this exercise will be on
- how to sort a pandas dataframe in python by index in Ascending order
- how to sort a pandas dataframe in python by index in Descending order
we will be using sort_index() method, by passing the axis arguments and the order of sorting, DataFrame can be sorted. By default, sorting is done in ascending order.
Let’s try with an example:
Create a dataframe:
import pandas as pd import numpy as np #Create a DataFrame d = { 'Name':['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine', 'Rahul','David','Andrew','Ajay','Teresa'], 'Age':[26,27,25,24,31,27,25,33,42,32,51,47], 'Score':[89,87,67,55,47,72,76,79,44,92,99,69]} df = pd.DataFrame(d) df=df.reindex([1,4,6,2,3,5,9,8,0,7,11,10]) print df
the resultant dataframe will be
sort the dataframe in python pandas by index in ascending order:
In the following code, we will sort the pandas dataframe by index in ascending order
# sort the pandas dataframe by index ascending df1=df.sort_index()
Sorting pandas dataframe by index in descending order:
In the following code, we will sort the pandas dataframe by index in descending order
# sort the pandas dataframe by index descending df2=df.sort_index(ascending=0)
kindly refer on sorting dataframe in python by column