Reverse row order in pandas
# Import modules
import pandas as pd
# Example dataframe
raw_data = {'fruit': ['Banana', 'Orange', 'Apple', 'lemon', "lime", "plum"],
'color': ['yellow', 'orange', 'red', 'yellow', "green", "purple"],
'kcal': [89, 47, 52, 15, 30, 28]
}
df = pd.DataFrame(raw_data, columns = ['fruit', 'color', 'kcal'])
df
fruit | color | kcal | |
---|---|---|---|
0 | Banana | yellow | 89 |
1 | Orange | orange | 47 |
2 | Apple | red | 52 |
3 | lemon | yellow | 15 |
4 | lime | green | 30 |
5 | plum | purple | 28 |
The rows of a dataframe can be reversed by using the loc accessor and passing ::-1
. This notation is the same as the one used to reverse a list in python
df.loc[::-1]
fruit | color | kcal | |
---|---|---|---|
5 | plum | purple | 28 |
4 | lime | green | 30 |
3 | lemon | yellow | 15 |
2 | Apple | red | 52 |
1 | Orange | orange | 47 |
0 | Banana | yellow | 89 |
If you want to reset the index as well so that the dataframe starts with a 0, you can combine what we just learned with the reset_index
method
df.loc[::-1].reset_index(drop=True)
fruit | color | kcal | |
---|---|---|---|
0 | plum | purple | 28 |
1 | lime | green | 30 |
2 | lemon | yellow | 15 |
3 | Apple | red | 52 |
4 | Orange | orange | 47 |
5 | Banana | yellow | 89 |
that way, the rows are in reverse order but the index column has been re-initialized so it starts with 0