Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • 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 Reference the Next Row in a 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 Reference the Next Row in a Pandas DataFrame

T

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?
    Sorting data is an important step in data analysis as it helps to organize and structure the information for easier interpretation and decision-making. Whether we're working with small datasets or large ones, sorting allows us to arrange data in a meaningful way. Pandas provides the sort_values() me
    5 min read
    How to Sort Pandas DataFrame?
    Sorting data is an important step in data analysis as it helps to organize and structure the information for easier interpretation and decision-making. Whether we're working with small datasets or large ones, sorting allows us to arrange data in a meaningful way. Pandas provides the sort_values() me
    5 min read
    How to Sort Pandas DataFrame?
    Sorting data is an important step in data analysis as it helps to organize and structure the information for easier interpretation and decision-making. Whether we're working with small datasets or large ones, sorting allows us to arrange data in a meaningful way. Pandas provides the sort_values() me
    5 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 access
    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
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
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