Reversing the order of rows in Pandas DataFrame

In this tutorial, we will discuss the different ways of reversing the order of rows in a Pandas DataFrame. This can be beneficial in various data analysis and preprocessing tasks and will help in handling data more efficiently.


We will be creating this Pandas DataFrame for use throughout this tutorial:

import pandas as pd

df = pd.DataFrame({
        'Name': ['John', 'Alice', 'Michael', 'Emma'],
        'Age': [25, 32, 28, 37],
        'City': ['New York', 'London', 'Paris', 'Sydney']
        })
      Name  Age      City
0     John   25  New York
1    Alice   32    London
2  Michael   28     Paris
3     Emma   37    Sydney

Reversing the order of rows in Pandas DataFrame using indexing:

We can use slicing to change the structure of the DataFrame. For example: [:] means to return all contents of the DataFrame. By default, the step value is assigned a value of 1. To change this, we must pass the step value after a second colon like so: [::2]. This will return the first row, then the third row, then the fifth row, and so on.

Similarly, we can pass -1 as the step value so that we iterate over the DataFrame in reverse order. This can be accomplished by accessing the DataFrame directly, or by using the loc[] or iloc[] methods.

Example 1:

df = df[ : : -1]
print(df)

Output:

      Name  Age      City
3     Emma   37    Sydney
2  Michael   28     Paris
1    Alice   32    London
0     John   25  New York

Example 2:

df = df.loc[ : : -1]
print(df)

Output:

      Name  Age      City
3     Emma   37    Sydney
2  Michael   28     Paris
1    Alice   32    London
0     John   25  New York

Example 3:

df = df.iloc[ : : -1]
print(df)

Output:

      Name  Age      City
3     Emma   37    Sydney
2  Michael   28     Paris
1    Alice   32    London
0     John   25  New York

As a result, all cases returned a DataFrame with a reversed order of rows.


Reversing the order of rows using the sort_index() method:

The sort_index() method changes the sorting order of the DataFrame. It takes ascending as a parameter which is a boolean variable. Furthermore, by passing False, we can change the sorting order to descending order.

Example:

df = df.sort_index(ascending=False)
print(df)

Output:

      Name  Age      City
3     Emma   37    Sydney
2  Michael   28     Paris
1    Alice   32    London
0     John   25  New York

However, this method comes with one caveat; it cannot be used to reverse the order if the indexes are not in ascending or descending order.


Reversing the order of rows using the reindex() method:

The reindex() method assigns new indexes to a Pandas DataFrame. It takes index as a parameter which is used to specify the new indexes to be assigned.

If we change the order of the indexes, the rows’ order will also be changed. To do this, we will apply the same logic used in the previous examples.

Example:

df = df.reindex(index = df.index[ : : -1])
print(df)

Output:

      Name  Age      City
3     Emma   37    Sydney
2  Michael   28     Paris
1    Alice   32    London
0     John   25  New York

As you can see, we passed a reversed list of indexes, thus changing the order of the whole DataFrame.


Reversing order of rows while keeping the values of the indexes:

All the techniques that we have discussed to this point involved reversing the order of indexes as well. If you want to maintain the index order while only changing the row order, you will have to use other techniques.

Example 1:

Using the reset_index() method we can reset the index order to the default order. By default, it adds a new column containing the old indexes. Among others, it takes drop as a parameter which can be used to remove the column containing the old indexes.

df = df[ : : -1].reset_index(drop=True)
print(df)

Output:

      Name  Age      City
0     Emma   37    Sydney
1  Michael   28     Paris
2    Alice   32    London
3     John   25  New York

Example 2:

If our indexes were any different from the default index values, we couldn’t use the previous method as it re-assigns the default indexes. We would need to create a copy of the DataFrame and store that in a new variable. Then we would reverse the entire DataFrame and re-assign the index using the copied DataFrame. Let’s demonstrate this with some code.

df = pd.DataFrame({
        'Name': ['John', 'Alice', 'Michael', 'Emma'],
        'Age': [25, 32, 28, 37],
        'City': ['New York', 'London', 'Paris', 'Sydney']
        }, index = [1, 2, 3, 4])

temp = df.copy()
df = df[ : : -1]

df.index = temp.index
print(df)

Output:

      Name  Age      City
1     Emma   37    Sydney
2  Michael   28     Paris
3    Alice   32    London
4     John   25  New York

Even after assigning a new value to the index, we still received the correct output.


This marks the end of the “Reversing the order of rows in Pandas DataFrame” Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Leave a Comment