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())
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_index()function to reset the index and also pass
Drop=Trueto drop all the old indices.
View all Courses