You can use the following basic syntax to reverse the rows in a pandas DataFrame:
df_reversed = df[::-1]
If you’d like to reverse the rows in the DataFrame and reset the index values, you can use the following syntax:
df_reversed = df[::-1].reset_index(drop=True)
The following example shows how to use this syntax in practice.
Example: How to Reverse a Pandas DataFrame
Suppose we have the following pandas DataFrame that contains information about various basketball players:
import pandas as pd #create DataFrame df = pd.DataFrame({'team': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], 'points': [18, 22, 19, 14, 14, 11, 20, 28], 'assists': [5, 7, 7, 9, 12, 9, 9, 4]}) #view DataFrame print(df) team points assists 0 A 18 5 1 B 22 7 2 C 19 7 3 D 14 9 4 E 14 12 5 F 11 9 6 G 20 9 7 H 28 4
We can use the following syntax to reverse the rows in the DataFrame:
#create new DataFrame with rows reversed df_reversed = df[::-1] #view new DataFrame print(df_reversed) team points assists 7 H 28 4 6 G 20 9 5 F 11 9 4 E 14 12 3 D 14 9 2 C 19 7 1 B 22 7 0 A 18 5
Notice that the order of the rows in the DataFrame have been reversed.
However, each row still contains its original index value.
If you’d like to reverse the rows of the DataFrame and reset the index values, you can use the following syntax:
#create reversed DataFrame and reset index values df_reversed = df[::-1].reset_index(drop=True) #view new DataFrame print(df_reversed) team points assists 0 H 28 4 1 G 20 9 2 F 11 9 3 E 14 12 4 D 14 9 5 C 19 7 6 B 22 7 7 A 18 5
Notice that the order of rows has been reversed and the index values have been reset.
Additional Resources
The following tutorials explain how to perform other common tasks in pandas:
How to Select Rows with NaN Values in Pandas
How to Find First Row that Meets Criteria in Pandas
How to Get Last Row in Pandas