Rearrange columns in Dataframe in Python – Pandas
In this tutorial, we will learn how to Rearrange columns in Dataframe in Python.
You are given a dataframe. Your task is to reorder/rearrange the data columns.
There are many methods to reorder/rearrange the data columns in Python.
- Using loc method
- Using iloc method
- By passing a list of column(s)
Preparation – Importing required libraries & creating dataset
import pandas as pd
#Creating test data to learn
data = {'Sr no': [1, 2, 3, 4, 5, 6],
'Name': ['Ram', 'Raju', 'Priya',
'Tinku', 'Monu', 'Mohan'],
'Age': [45, 16, 18, 34, 25, 20]}
df = pd.DataFrame(data = data)
print("Original Dataframe")
print(df)Original Dataframe:
Sr no | Name | Age
0 1 | Ram | 45
1 2 | Raju | 16
2 3 | Priya | 18
3 4 | Tinku | 34
4 5 | Monu | 25
5 6 | Mohan | 20
Method 1 – Using loc method
In this, we will pass the different columns name(s) in the loc to change the order of dataframe columns.
#Passing the column names in the list format
print("Rearranged dataframe using loc")
df.loc[:,['Age','Name','Sr no']] Rearranged dataframe using loc
Age | Name | Sr no
0 45 | Ram | 1
1 16 | Raju | 2
2 18 | Priya | 3
3 34 | Tinku | 4
4 25 | Monu | 5
5 20 | Mohan | 6
Method 2 – Using iloc method
In this, we will pass the column index in the iloc to change the order of dataframe columns.
#Passing the column names in the list format
print("Rearranged dataframe using iloc")
df.iloc[:,[1,2,0]] Rearranged dataframe using iloc
Name | Age | Sr no
0 Ram | 45 | 1
1 Raju | 16 | 2
2 Priya | 18 | 3
3 Tinku | 34 | 4
4 Monu | 25 | 5
5 Mohan | 20 | 6
Method 3 – By passing a list of column(s)
In this, we will pass the list of columns in the desired sequence to change the order of dataframe columns.
#Passing the column names in the list format
print("Rearranged dataframe by passing list")
df[['Age', "Name", "Sr no"]] Rearranged dataframe by passing list
Age | Name | Sr no
0 45 | Ram | 1
1 16 | Raju | 2
2 18 | Priya | 3
3 34 | Tinku | 4
4 25 | Monu | 5
5 20 | Mohan | 6We’ve successfully learned to Rearrange columns in Dataframe in Python, simplifying the solution for better understanding. I hope you found this tutorial enjoyable!
Leave a Reply