Home »
Python »
Python Programs
Combine two pandas dataframes with the same index
Given two pandas dataframes, we have to combine them with the same index.
By Pranit Sharma Last updated : September 30, 2023
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.
Problem statement
We are given two DataFrames with the same index but different columns, we need to combine the two DataFrames with the same index but all the columns.
Combining two pandas dataframes with the same index
We will use pandas.concat() method for this purpose. The pandas.concat() is a method of combining or joining two DataFrames. It is used to combine DataFrames but it is a method that appends or inserts one (or more) DataFrame below the other.
Let us understand with the help of an example,
Python program to combine two pandas dataframes with the same index
# Importing pandas package
import pandas as pd
# Creating dictionaries
d1 = {
'party':['BJP','INC','AAP'],
'state':['MP','RAJ','DELHI']
}
d2 = {
'leader':['Modi','Shah','Kejriwal'],
'position':['PM','HM','CM']
}
# Creating DataFrame
df = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)
# Display the DataFrame
print("Original DataFrame 1:\n",df,"\n")
print("Original DataFrame 2:\n",df2,"\n")
# Combining two DataFrames
res = pd.concat([df,df2],axis=1)
# Display result
print("Result:\n",res,"\n")
Output
The output of the above program is:
Python Pandas Programs »