How to Reverse Rows of pandas DataFrame in Python (Example Code)

In this tutorial, I’ll explain how to reverse the rows of a pandas DataFrame in the Python programming language.

Preparing the Example

import pandas as pd                                # Load pandas library
my_df = pd.DataFrame({"col1":list(range(5, 10)),  # Construct example data in Python
                      "col2":["a", "b", "a", "c", "c"],
                      "col3":list(range(19, 14, - 1))})
print(my_df)                                      # Displaying example data
#    col1 col2  col3
# 0     5    a    19
# 1     6    b    18
# 2     7    a    17
# 3     8    c    16
# 4     9    c    15

Example: Reverse Ordering of pandas DataFrame in Python

my_df = my_df[::-1]                               # Reversing rows
print(my_df)                                      # Displaying updated data
#    col1 col2  col3
# 4     9    c    15
# 3     8    c    16
# 2     7    a    17
# 1     6    b    18
# 0     5    a    19

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top