In this short guide, you’ll see how to change the order of columns in Pandas DataFrame.
Here are the steps:
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:
Name | Age | Profession | Country |
Jack | 22 | Accountant | Italy |
Maria | 31 | Engineer | Spain |
Emma | 43 | Doctor | Brazil |
Rick | 25 | Lawyer | Mexico |
Sophia | 52 | Banker | France |
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) print(df)
Run the code in Python, and you’ll get the following DataFrame:
Name Age Profession Country
0 Jack 22 Accountant Italy
1 Maria 31 Engineer Spain
2 Emma 43 Doctor Brazil
3 Rick 25 Lawyer Mexico
4 Sophia 52 Banker France
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 the 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) df = df[['Name', 'Country', 'Age', 'Profession']] print(df)
Once you run the code, you’ll get the following DataFrame with the ordered columns:
Name Country Age Profession
0 Jack Italy 22 Accountant
1 Maria Spain 31 Engineer
2 Emma Brazil 43 Doctor
3 Rick Mexico 25 Lawyer
4 Sophia France 52 Banker
You may also wish to check the following page for additional Python tutorials.