Press "Enter" to skip to content

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 with reversing the order completely. After we have learned how to do that we continue by reversing the order of the rows. That is, pandas data frame can be reversed such that the last column becomes the first or such that the last row becomes the first.

Data to Work With

First, we create some example data using normal and binomial from numpy.random.  Using normal we create two different response time variables (response times are often used in experimental psychology) and binomial is used to create response accuracy (also often used in psychology experiments).

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

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

Reversing Pandas Dataframe by Column

We are going to start with changing places of the first (“Accuracy) and last column (“Sub_id”).
First, we create a list of the column names and swapping the first item to the last:

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

We can sort our dataframe ascending again (i.e., alphabetical):

You can also reverse pandas dataframe completely. The second line (columns[::-1]) reverse the list of column names. Third, the dataframe is reversed using that list.

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 the dataframe ascending:

First, we will use iloc which is integer based.

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.

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.

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.

Be First to Comment

Leave a Reply

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.

%d bloggers like this: