Home »
Python »
Python Programs
Python - How to swap two dataframe columns?
Given a Pandas DataFrame, we have to swap its two columns.
Submitted by Pranit Sharma, on August 21, 2022
Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.
Swap two dataframe columns
Swapping two dataframe columns is like interchanging the values of two columns.
Pandas provides us a special feature or method called DataFrame.reindex() which is used for swapping two columns at a time, it takes a list of columns that needs to be swapped inside it as a parameter.
To solve this problem, we will first create a DataFrame of the student, with columns like Name, Age, Roll_No, Class, School, Percentage, and then we will interchange the column Roll_No with Age.
For this purpose, we will encapsulate these two columns in a list and we will assign this list to a variable called swap_list. We will then use DataFrame.reindex() inside which we will pass our swap_list.
pandas.DataFrame.reindex() syntax:
DataFrame.reindex(
labels=None,
index=None,
columns=None,
axis=None,
method=None,
copy=True,
level=None,
fill_value=nan,
limit=None,
tolerance=None
)
Let us understand with the help of an example,
Python program to swap two dataframe columns
# Importing pandas package
import pandas as pd
# Creating a dictionary
d = {
'Name':['Ram','Shyam','Seeta','Geeta'],
'Age':[16,17,15,16],
'Roll_No':[101,102,103,104],
'Class':['XII','XI','X','XI']
}
# Creating a DataFrame
df = pd.DataFrame(d)
# Display Original DataFrame
print("Created DataFrame:\n",df,"\n")
# creating a list of columns
swap_list = ["Name","Roll_No","Age","Class"]
# Swapping the columns
df = df.reindex(columns=swap_list)
# Display modified DataFrame
print("Modified DataFrame:\n",df)
Output
The output of the above program is:
Python Pandas Programs »