Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Data preprocessing
  • Data Manipulation
  • Data Analysis using Pandas
  • EDA
  • Pandas Exercise
  • Pandas AI
  • Numpy
  • Matplotlib
  • Plotly
  • Data Analysis
  • Machine Learning
  • Data science
Open In App
Next Article:
How to rename columns in Pandas DataFrame
Next article icon

How to Reverse Row in Pandas DataFrame?

Last Updated : 15 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to reverse a row in a pandas data frame using Python. 

With the help of Pandas, we can perform a reverse operation by using loc(), iloc(), reindex(), slicing, and indexing on a row of a data set. 

Creating Dataframe

Let’s create a simple data frame with a dictionary, say column names are: ‘Income’, ‘Expenses’, ‘Profit’.

Python3
# Import pandas package import pandas as pd  # Define a dictionary containing employee data data = {'Income': [150000, 13000, 11000, 11000],         'Expenses': [10000, 11000, 7000, 50000],         'Profit': [5000, 2000, 4000, 6000]         }   # Convert the dictionary into DataFrame dataframe = pd.DataFrame(data)  # Observe the result dataframe 

Output:

 Reverse Row in Pandas DataFrame
 

Using iloc() function to Reverse Row

Reversing the rows of a data frame in pandas can be done in python by invoking the iloc() function.  Let us know how to reverse the rows of a data frame in pandas.

Syntax: DataFrame.iloc[]

Parameters: Index Position: Index position of rows in integer or list of integer.

Return: Data frame or Series depending on parameters

Python3
# Reverse rows using iloc() Function Data_reverse_row_1 = dataframe.iloc[::-1]  # Observe the result Data_reverse_row_1 

Output:

Reverse Row in Pandas DataFrame
reversed database

Using loc() function to Reverse Row

Reversing the rows of a data frame in pandas can be done in python by invoking the loc() function. The panda's dataframe.loc() attribute accesses a set of rows and columns in the given data frame by either a label or a boolean array.

Syntax: DataFrame.loc()

Parameter : None

Returns : Scalar, Series, DataFrame

Python3
# Reverse rows using iloc() Function Data_reverse_row_2 = dataframe.loc[::-1]  # Observe the result Data_reverse_row_2 

Output:

 Reverse Row in Pandas DataFrame
 

Note: .loc() and .iloc() use the indexers to select for indexing operators.

Using reindex() function to Reverse Row

Reverse rows of the data frame using reindex() Function. The pandas dataframe.reindex() function concatenates the dataframe to a new index with optional filling logic, placing NA/NaN at locations that have no value in the previous index.

Syntax: DataFrame.reindex(index=None)

Parameter : index, columns : New labels / index to conform to. Preferably an Index object to avoid duplicating data

Returns : reindexed : DataFrame

Python3
# reversing a DataFrame # retrieving row by reindex method df.reindex(index=dataframe.index[::-1]) 

Output:

 Reverse Row in Pandas DataFrame
 

Using dataframe indexing to Reverse Row

Reverse rows using data frame indexing in python. In Python, we can set the index of a dataframe in reverse. In this method, we create a Python list and pass it's an index to the dataframe() function's index parameter. Let's implement this through Python code.

Syntax: DataFrame[start:end:slicing]

Python3
# Reverse slicing columns in data frame dataframe[::-1] 

Output:

 Reverse Row in Pandas DataFrame
 

Using the reset_Index() function to Reverse Row

Here we use the reset_index() function to reset the index for the entire database and also pass Drop=True to drop all old indices.

Python3
# Here we are just resetting the indexing for the entire database # and reversing the database.  d = dataframe.loc[::-1].reset_index(drop=True).head() print(d) 

Output:

 Reverse Row in Pandas DataFrame
reversed database

Next Article
How to rename columns in Pandas DataFrame
author
tanushree_dev
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Python-pandas
  • Python pandas-dataFrame
  • Python Pandas-exercise
Practice Tags :
  • python

Similar Reads

  • How to Reference the Next Row in a Pandas DataFrame
    To reference the next row in a Pandas DataFrame, you can use the .shift() method. This method shifts the data by a specified number of periods (rows), allowing you to access the previous or next row's values in a given column. It's useful for comparing consecutive rows or calculating differences bet
    4 min read
  • How to Sort Pandas DataFrame?
    Pandas provides a powerful method called sort_values() that allows to sort the DataFrame based on one or more columns. The method can sort in both ascending and descending order, handle missing values, and even apply custom sorting logic. To immediately understand how sorting works, let’s look at a
    6 min read
  • How to get nth row in a Pandas DataFrame?
    Pandas Dataframes are basically table format data that comprises rows and columns. Now for accessing the rows from large datasets, we have different methods like iloc, loc and values in Pandas. The most commonly used method is iloc(). Let us consider a simple example. Method 1. Using iloc() to acces
    4 min read
  • Pandas DataFrame.reset_index()
    In Pandas, reset_index() method is used to reset the index of a DataFrame. By default, it creates a new integer-based index starting from 0, making the DataFrame easier to work with in various scenarios, especially after performing operations like filtering, grouping or multi-level indexing. Example
    3 min read
  • How to rename columns in Pandas DataFrame
    In this article, we will see how to rename column in Pandas DataFrame. The simplest way to rename columns in a Pandas DataFrame is to use the rename() function. This method allows renaming specific columns by passing a dictionary, where keys are the old column names and values are the new column nam
    4 min read
  • Reset Index in Pandas Dataframe
    Let’s discuss how to reset the index in Pandas DataFrame. Often We start with a huge data frame in Pandas and after manipulating/filtering the data frame, we end up with a much smaller data frame. When we look at the smaller data frame, it might still carry the row index of the original data frame.
    6 min read
  • Pandas - How to reset index in a given DataFrame
    Let us see how to reset the index of a DataFrame after dropping some of the rows from the DataFrame.Approach :  Import the Pandas module.Create a DataFrame.Drop some rows from the DataFrame using the drop() method.Reset the index of the DataFrame using the reset_index() method.Display the DataFrame
    1 min read
  • How to Set Cell Value in Pandas DataFrame?
    In this article, we will discuss how to set cell values in Pandas DataFrame in Python. Method 1: Set value for a particular cell in pandas using dataframe.at This method is used to set the value of an existing value or set a new record. [GFGTABS] Python3 # import pandas module import pandas as pd #
    2 min read
  • How to Get First Row of Pandas DataFrame?
    To get the first row of a Pandas Dataframe there are several methods available, each with its own advantages depending on the situation. The most common methods include using .iloc[], .head(), and .loc[]. Let's understand with this example: [GFGTABS] Python import pandas as pd data = {'Name'
    4 min read
  • Remove last n rows of a Pandas DataFrame
    Let's see the various methods to Remove last n rows of a Pandas Dataframe.First, let's make a dataframe: [GFGTABS] Python3 # Import Required Libraries import pandas as pd # Create a dictionary for the dataframe dict = { 'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences