How to Reverse Row Order in Pandas Dataframes

This tutorial shows two methods to reverse row order based on the dataframe index. The following shows the key syntax code.

Method 1:

df_name[::-1.]

Method 2:

df_name.loc[::-1.]


Example 1 for Method 1

We can reverse row order in Python Pandas dataframes using car_data[::-1].

import pandas as pd

# create a new dataframe
car_data = {'Unique_Number': ['12', '89','63','43'], 
    'Brand': ['Tesla', 'Tesla','Tesla','Ford'], 
     'Location': ['CA', 'CA','NY','MA'],
    'Year':['2019','2018','2020','2019']}
car_data=pd.DataFrame(data=car_data)

# print out the dataframe
print('Original Dataframe: \n',car_data)

# reverse the order of the dataframe
car_data_reversed=car_data[::-1]

# print out the reversed dataframe
print('Reversed Dataframe: \n',car_data_reversed)

Below shows the original dataframe and the reversed dadaframe based on the index.

Original Dataframe: 
   Unique_Number  Brand Location  Year
0            12  Tesla       CA  2019
1            89  Tesla       CA  2018
2            63  Tesla       NY  2020
3            43   Ford       MA  2019

Reversed Dataframe: 
   Unique_Number  Brand Location  Year
3            43   Ford       MA  2019
2            63  Tesla       NY  2020
1            89  Tesla       CA  2018
0            12  Tesla       CA  2019

Example 2 for method 2

We can also use car_data.loc[::-1] to reverse the row order and the following is the Python code example.

import pandas as pd

# create a new dataframe
car_data = {'Unique_Number': ['12', '89','63','43'], 
    'Brand': ['Tesla', 'Tesla','Tesla','Ford'], 
     'Location': ['CA', 'CA','NY','MA'],
    'Year':['2019','2018','2020','2019']}
car_data=pd.DataFrame(data=car_data)

# print out the dataframe
print('Original Dataframe: \n',car_data)

# reverse the order of the dataframe
car_data_reversed=car_data.loc[::-1]

# print out the reversed dataframe
print('Reversed Dataframe: \n',car_data_reversed)

The following is the output, which shows the reversed dataframe.

Original Dataframe: 
   Unique_Number  Brand Location  Year
0            12  Tesla       CA  2019
1            89  Tesla       CA  2018
2            63  Tesla       NY  2020
3            43   Ford       MA  2019

Reversed Dataframe: 
   Unique_Number  Brand Location  Year
3            43   Ford       MA  2019
2            63  Tesla       NY  2020
1            89  Tesla       CA  2018
0            12  Tesla       CA  2019

Further Reading