The world’s leading publication for data science, AI, and ML professionals.

4 Methods for Changing the Column Order of a Pandas Data Frame

Explained with examples.

Photo by Elena Mozhvilo on Unsplash
Photo by Elena Mozhvilo on Unsplash

Pandas is one of the most popular tools in the Data Science ecosystem. It is a Python library for data analysis and manipulation.

Pandas provides numerous functions and methods to handle tabular data efficiently. You can easily clean, manipulate, or process data stored in a data frame.

A Pandas data frame consists of labelled rows and columns. In this article, we will go over 4 methods to change the order of columns in a data frame. It may sound like a too specific task. However, there will be cases where you need to update column order.


If you’d like to learn more about Pandas, visit my course 500 Exercises to Master Python Pandas.


Let’s start with importing libraries and creating a sample data frame.

import numpy as np
import pandas as pd
df = pd.DataFrame({
   "A": np.random.randint(10, size=5),
   "B": np.random.randint(20, size=5),
   "C": np.random.randint(5, size=5),
   "D": np.random.randint(30, size=5)
})
df
(image by author)
(image by author)

We have a data frame with 4 columns and 5 rows. The values are random integers generated by the randint function of Numpy.


First method

We can use the iloc method to change or update the order of columns as below:

df.iloc[:, [2,3,1,0]]
(image by author)
(image by author)

The iloc method works with indices. The colon before the comma indicates that we want all the rows. The list after the comma contains the column indices. We can put the indices in any order as long as it exists in the data frame.


Second method

The loc method is similar to the iloc method but it works with labels instead of indices. Thus, we can reorder the columns by creating a list with column labels.

df.loc[:, ["B","D","C","A"]]
(image by author)
(image by author)

We do not have to select all the rows and columns. Both loc and iloc methods allow for selection a subset of rows and columns.

For instance, we can select the first 3 rows and columns A and C as below:

df.loc[:3, ["C","A"]]

It is important to note that the row labels and indices of a data frame are the same. Pandas assigns integer labels to rows by default. Unless we change the row labels, how we select rows with loc and iloc methods are the same.


Third method

Pandas also allows for selecting a subset of columns by passing a list as below:

df[["A","D","C","B"]]
(image by author)
(image by author)

It is similar to the loc and iloc methods but we do not have any control over which rows to be selected. All the columns are selected, we can only specify the column names and order.


Fourth method

This method can be considered as a special case of the third method. It involves some features of base Python such as reversing a list.

Consider a case where we have a data frame with a high number of rows and we need to reverse the order of columns.

We can create a list of columns and reverse it. This reverse list can be used to select columns just like the third method.

cols = list(df.columns)
cols.reverse()
df[cols]
(image by author)
(image by author)

The reverse method of Python works in place. Thus, it does not return anything but reverses the list.

We can also reverse a list by using indexing. Here is a different way of performing the same operation.

cols = list(df.columns)
df[cols[::-1]]

The expression "[::-1]" selects all items in a list with a step size of -1. Thus, it does the selection by going backwards. As a result, the list is reversed.


Conclusion

What we have covered in this article demonstrates how to change the order of columns in a data frame. These methods can also be used for selecting a subset of a data frame.

A typical use case of changing the column order is when we need to combine multiple data frames. If the data frames are combined or concatenated along the rows axis (i.e. on top of each other), the order of columns must be the same.

Thank you for reading. Please let me know if you have any feedback.


Related Articles