How to Change the Order of Columns in Pandas DataFrame

In this short guide, you’ll see how to change the order of columns in Pandas DataFrame.

An example is included for illustration purposes.

Steps to Change the Order of Columns in Pandas DataFrame

Step 1: Prepare the Data for the DataFrame

To begin, prepare the data for your DataFrame.

For example, the following dataset was prepared:

NameAgeProfessionCountry
Jack22AccountantItaly
Maria31EngineerSpain
Emma43DoctorBrazil
Rick25LawyerMexico
Sophia52BankerFrance

Step 2: Create the DataFrame

Now create the actual DataFrame based on the above dataset:

import pandas as pd

data = {'Name': ['Jack','Maria','Emma','Rick','Sophia'],
        'Age': [22,31,43,25,52],
        'Profession': ['Accountant','Engineer','Doctor','Lawyer','Banker'],
        'Country': ['Italy','Spain','Brazil','Mexico','France']     
        }

df = pd.DataFrame(data, columns= ['Name','Age','Profession','Country'])

print (df)

Run the code in Python, and you’ll get the following DataFrame:

How to Change the Order of Columns in Pandas DataFrame

As you can see, the order of the columns is:

Name, Age, Profession, Country

Step 3: Change the Order of the Columns in the DataFrame

Let’s say that you want to change the order of the columns to:

Name, Country, Age, Profession

In that case, you’ll need to add the following syntax to the code:

df = df[['Name','Country','Age','Profession']]

So this is the complete code to reorder your columns in the DataFrame:

import pandas as pd

data = {'Name': ['Jack','Maria','Emma','Rick','Sophia'],
        'Age': [22,31,43,25,52],
        'Profession': ['Accountant','Engineer','Doctor','Lawyer','Banker'],
        'Country': ['Italy','Spain','Brazil','Mexico','France']     
        }

df = pd.DataFrame(data, columns= ['Name','Age','Profession','Country'])
df = df[['Name','Country','Age','Profession']]

print (df)

Once you run the code, you’ll get the DataFrame below with the ordered columns:

Change the Order of Columns in Pandas DataFrame

You may also wish to check the following page for additional tutorials about Python.