Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pandas
python
communitycreator

How to reverse the row order in a DataFrame in pandas

Harsh Jain

In this shot, we will discuss how we can reverse the row order when we print the DataFrame, i.e., we will print the DataFrame in the reverse order.

Let’s first create a DataFrame, and then print it in the reversed order.

import pandas as pd

drinks = pd.read_csv('http://bit.ly/drinksbycountry')
drinks = drinks[["country", 
                "beer_servings", 
                "wine_servings",
                "continent"
              ]]
print("Original DataFrame: \n",drinks.head())

print("\nReversed the row order:\n",drinks.loc[::-1].head())
Print the DataFrame in the reverse order

Explanation

  • In line 1, we import the required package.
  • In line 3, we read the data in the DataFrame and store it in the drinks variable.
  • In line 4, we only take three columns for readability purposes.
  • In line 9, we print the DataFrame drinks.
  • In line 11, we print the DataFrame in the reverse order.

Note: here we used ::-1, which is the same slicing notation used to reverse a Python list.

Now, as we can see in the output, the index does not start with zero. So, how can we make the indices start with zero?

Let’s look at the code snippet below:

drinks = drinks.loc[::-1].reset_index(drop=True).head()
print(drinks)
Reset the index of a DataFrame in Pandas

Explanation

  • In line 1, we use the reset_index() function to reset the index and also pass Drop=True to drop all the old indices.
  • In line 2, we print the reversed rows. We can see that the rows are reversed and the index has been reset to a default integer index.

RELATED TAGS

pandas
python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring