Home »
Python »
Python Programs
Pandas join dataframe with a force suffix
Given two pandas dataframes, we have to join them with a force suffix.
By Pranit Sharma Last updated : October 03, 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.
Joining dataframe with a force suffix
A suffix is a substring that is connected at the end of any string.
Here, we are having two DataFrames and we need to join these two DataFrames also, we need to join a suffix on the columns of the joined DataFrame.
We will join the two DataFrames with the help of the pandas.DataFrame.join() method, but this may collide the columns, so we will add a specific suffix at the end of each column name of the DataFrames,
The pandas.DataFrame.join() is a method of combining or joining two DataFrames, join method allows us to combine the DataFrames based on the index i.e., the row value.
Let us understand with the help of an example,
Python program to join dataframe with a force suffix
# Importing pandas package
import pandas as pd
# Creating two dictionaries
d1 = {'A':[1,2],'B':[3,4]}
d2 = {'A':[5,6],'B':[7,8]}
# Creating DataFrames
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)
# Display original DataFrames
print("Original Dataframe 1:\n",df1,"\n")
print("Original Dataframe 2:\n",df2,"\n")
# Adding suffix at the end of each column
df1.columns = df1.columns.map(lambda x: str(x) + '_a')
df2.columns = df2.columns.map(lambda x: str(x) + '_b')
# Joining two DataFrames
new_df = df1.join(df2)
# Display new DataFrame
print("New DataFrame:\n",new_df)
Output
The output of the above program is:
Python Pandas Programs »