Yes, you can reverse the rows of a DataFrame in pandas.
One way to do this is by using the iloc method and specifying the slice notation [::-1] to reverse the order of the rows.
For example, suppose you have the following DataFrame:
In [3]:
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35],
'country': ['USA', 'Canada', 'Mexico']
})
print(df)
name age country 0 Alice 25 USA 1 Bob 30 Canada 2 Charlie 35 Mexico
To reverse the rows of this DataFrame, you can use the iloc method and the slice notation [::-1] as follows:
In [4]:
df_reverse = df.iloc[::-1]
print(df_reverse)
name age country 2 Charlie 35 Mexico 1 Bob 30 Canada 0 Alice 25 USA
As you can see, the order of the rows has been reversed. Note that this method does not modify the original DataFrame but returns a new DataFrame with the rows reversed. If you want to modify the original DataFrame, you can use the inplace=True parameter with the iloc method.
Comments
Post a Comment