Reindex or Rearrange rows in python pandas – change order of row in pandas

In this tutorial we will learn how to reindex in python pandas or change the order of the rows in python pandas with the help of reindex() function. Rearrange the rows in python in ascending order and Rearrange the rows in pandas descending order is explained.  We will discuss the example for

  • Reindexing or changing the order of Rows in pandas python
  • Rearrange rows in ascending order pandas python
  • Rearrange rows in descending order pandas python

Create dataframe:

######## Create a DataFrame

import pandas as pd
import numpy as np


d = {
    'Name':['Alisa','Bobby','Cathrine','Madonna','Rocky','Sebastian','Jaqluine',
   'Rahul','David','Andrew','Ajay','Teresa'],
   'Score1':[62,47,55,74,31,77,85,63,42,32,71,57],
   'Score2':[89,87,67,55,47,72,76,79,44,92,99,69],
   'Score3':[56,86,77,45,73,62,74,89,71,67,97,68]}

df = pd.DataFrame(d)
df

The resultant dataframe will be

change order of column and rows in pandas dataframe 1

 

 

Reindex or change the order of rows in pandas python:

Now lets change the order of rows as shown below


##### reindex or change the order of rows

df.reindex([8,11,9,2, 1, 0,7,5,6,4,10,3])

so the re indexed dataframe will be

change order of column and rows in pandas dataframe 2

 

 

Rearrange rows in ascending order pandas python

We will be using sort_index() Function with axis=0 to sort the rows and with ascending =True will sort the rows in ascending order

###### Rearrange rows in ascending order pandas python

df.sort_index(axis=0,ascending=True)

So the resultant table with rows sorted in ascending order will be

Reindex or Rearrange in python pandas – change order of row in pandas 3

 

 

Rearrange rows in descending order pandas python

We will be using sort_index() Function with axis=0 to sort the rows and with ascending =False will sort the rows in descending order

##### Rearrange rows in descending order pandas python

df.sort_index(axis=0,ascending=False) 

So the resultant table with rows sorted in descending order will be

Reindex or Rearrange in python pandas – change order of row in pandas 4

 

 

previous-small Reindex in python – change order of column and rows in pandas dataframe                                                                                                          next_small Reindex in python – change order of column and rows in pandas dataframe

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