sort the dataframe in python pandas by index

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

 

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()

sort the dataframe in python pandas by index 2

 

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)

sort the dataframe in python pandas by index 3

kindly refer on sorting dataframe in python by column 

previous Sorting pandas dataframe by index in python 1                                                                                                           next Sorting pandas dataframe by index in python 1

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts