Reverse Rows in Pandas DataFrame in Python
In this tutorial, let’s see how to reverse rows in Pandas DataFrame in Python because you might encounter situations where reversing rows in a DataFrame is needed. Pandas is a Python library used for data manipulation and analysis, and it has a 2-dimensional data structure called DataFrame with rows and columns.
First, import the Pandas package with an alias name.
Reverse Rows in Pandas DataFrame in Pythonimport pandas as pd
I created a new DataFrame for reversing rows by creating a dictionary named data and converting it into a Pandas DataFrame.
data = { "Fruits" : ["Mango", "Orange", "Papaya", "Guava", "Apple"], "Prices": [100, 35, 70, 20, 120] } df = pd.DataFrame(data) print(df)
Output:
Fruits Prices 0 Mango 100 1 Orange 35 2 Papaya 70 3 Guava 20 4 Apple 120
Reverse Rows in Pandas DataFrame in Python
We can use the indexing concept in Python to reverse rows of a DataFrame, as shown below. Here I used the reset_index() method to reset the indexes after modifying the rows of a DataFrame, as they might still have their original index numbers before the modification. The arguments to the function will make the default index as index by resetting our own index.
rdf = df[::-1] rdf.reset_index(inplace=True, drop=True) print(rdf)
Output:
Fruits Prices 0 Apple 120 1 Guava 20 2 Papaya 70 3 Orange 35 4 Mango 100
There are many ways to achieve the same result, and let’s implement them below.
Using iloc()
Using the iloc()
function, we can access the values of DataFrame with indexes. By using indexing, we can reverse the rows in the same way as before.
rdf = df.iloc[::-1] rdf.reset_index(inplace=True, drop=True) print(rdf)
Using loc()
Access the values of the DataFrame with labels using the loc()
function. Then use the indexing property to reverse the rows of a DataFrame, as shown before.
rdf = df.loc[::-1] rdf.reset_index(inplace=True, drop=True) print(rdf)
Using reindex()
Use the reindex method to reverse the rows of the DataFrame.
rdf = df.reindex(index = df.index[::-1]) rdf.reset_index(inplace=True, drop=True) print(rdf)
Using sort_index()
Use the sort_index()
method to sort the rows in descending order.
rdf = df.sort_index(ascending=False) rdf.reset_index(inplace=True, drop=True) print(rdf)
Using a for loop
Use a for loop to iterate through DataFrame in reverse and add all rows to a new array. Then convert the array into a Pandas DataFrame.
res = [] for i in reversed(df.index): temp = [] temp.append(df['Fruits'][i]) temp.append(df['Prices'][i]) res.append(temp) rdf = pd.DataFrame(res, columns = ['Fruits', 'Prices']) print(rdf)
The output of all the above programs will be
Fruits Prices 0 Apple 120 1 Guava 20 2 Papaya 70 3 Orange 35 4 Mango 100
Leave a Reply