Six Ways to Reverse Pandas dataframe

In this post, we will learn how to reverse Pandas’ dataframe. We start by changing the first column with the last column and continue reversing the order completely. After we have learned how to swap columns in the dataframe and reverse the order by the columns, we continue by reversing the order of the rows. Pandas dataframe can be reversed such that the last column becomes the first or the last row becomes the first.

Table of Contents

Data to Work With

First, we need to create some example data to reverse. Here we will use the methods normal and binomial from numpy.random.  Using the normal method, we create two different response time variables (response times are often used in experimental psychology), and the binomial method is used to create response accuracy (also often used in psychology experiments).

How to Create a Pandas dataframe

We will use Pandas to create a dataframe from the data. Note the simulation of data is not intended to be used for anything other than for us to have data to create a Pandas dataframe.

import pandas as pd
import numpy as np

distracted = [1 for i in xrange(15)]
normal_perf = [0 for i in xrange(15)]

sex = ['Male' if i%2 == 0 else 'Female' for i in xrange(30)]

rt_distracted = np.random.normal(1660, 100, 15)
rt_normal_perf = np.random.normal(1054, 97, 15)

accuracy_distracted = np.random.binomial(1, .79, 15)
accuracy_normal_perf = np.random.binomial(1, .87, 15)

rt = np.concatenate((rt_distracted, rt_normal_perf))
acc = np.concatenate((accuracy_distracted, accuracy_normal_perf))

subject_id = [i for i in xrange(1,31)]

data = {'Sub_id':subject_id, 'Condition':distracted, 'RT':rt, 
         'Accuracy':acc, 'Gender':sex}
data_frame = pd.DataFrame(data)Code language: Python (python)
Pandas Dataframe Object
  • Save
Output of data_frame.head()

Learn how to work with Pandas dataframe (e.g., read csv & excel,  subset, and group) here.

Reversing Pandas Dataframe by Column

This section will teach how to reverse Pandas dataframe by column.
First, we are going to start with changing places of the first (“Accuracy) and last column (“Sub_id”).

How to Swap Columns in a dataframe

In the example below, we create a list of the column names and swap the first item to the last in the list.

columns = data_frame.columns.tolist()
columns = columns[-1:] + columns[:-1]Code language: Python (python)

Then we continue using the created list, and the columns in the dataframe will change places. That is, we reverse the data frame by column. Pretty easy:

data_frame = data_frame[columns]
data_frame.head()Code language: Python (python)
  • Save
First and last column have changed places

How to Order a Pandas Dataframe alphabetically

In this section, we are going to order a Pandas dataframe alphabetically. That is, we are going to sort our dataframe ascending (i.e., alphabetical):

data_frame = data_frame.sort_index(axis=1 ,ascending=True)
data_frame.head()Code language: Python (python)

How to Reverse the Order of the Columns

In this section, we will learn how to reverse the order of the columns in the dataframe. That is, we can also reverse pandas dataframe completely. In the code example below, the second line (columns[::-1]) reverse the list of column names. Third, the dataframe is reversed using that list.

columns = data_frame.columns.tolist()
columns = columns[::-1]
data_frame = data_frame[columns]Code language: Python (python)

How to Reverse a Single Column

In this Pandas reverse dataframe example, we will reverse only one of the columns.

data_frame["Sub_id"] = data_frame["Sub_id"].values[::-1]
data_frame.head()Code language: Python (python)
  • Save

Reverse Pandas Dataframe by Row

Pandas dataframe object can also be reversed by row. That is, we can get the last row to become the first.  We start by re-orderíng the dataframe ascending. Note in the example below, we use the axis argument and set it to “1”. This will make Pandas sort over the rows instead of the columns.

data_frame = data_frame.sort_index(axis=1 ,ascending=True)Code language: Python (python)

First, we will use iloc which is integer based to reverse the order of the Pandas dataframe:

data_frame = data_frame.iloc[::-1]Code language: Python (python)
  • Save

However, we can also use sort_index by using the axis 0 (row). The code below will, of course, reverse the dataframe back to the one we started with.

data_frame = data_frame.sort_index(ascending=True, axis=0)Code language: Python (python)

Lastly, we can also use the method reindex to reverse by row. This will sort Pandas Dataframe reversed. That is, the last element will be first.

data_frame = data_frame.reindex(index=data_frame.index[::-1])
data_frame.head()Code language: Python (python)

That was it; six ways to reverse Pandas Dataframe. You can go to my GitHub-page to get a Jupyter notebook with all the above code and some output: Jupyter notebook. Now that you know how to reverse columns and rows in, you might also want to know how to rename columns in Pandas.

  • Save

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
Share via
Copy link
Powered by Social Snap