Mapping columns from one dataframe to another to create a new column

Given a pandas dataframe, we have to map columns from one dataframe to another to create a new column.
By Pranit Sharma Last updated : October 02, 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.

Mapping columns from one dataframe to another

For this purpose, we will use DataFrame.merge() method, merge method combines the second DataFrame with the first DataFrame, but the key point is, it merges on the basis of a column key and we can say if we have two DataFrame with same column "Age", merge method will work in such a way that on merging the two DataFrames on "Age", all the rows having common age from both DataFrames are merged together whereas the column which has unique Age will produce Nan values when merged.

Let us understand with the help of an example,

Python program to map columns from one dataframe to another to create a new column

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {
    'id':[1,2,3],
    'Brand':['Samsung','LG','Sony'],
    'Product':['Phones','Fridge','Speakers']
}

d2 = {
    's no':[1,2,3],
    'Brand_name':['Samsung','LG','Sony'],
    'Warehouse':['Madison','Gurugram','Pune']
}

# Creating DataFrames
df1 = pd.DataFrame(d1)
df2 = pd.DataFrame(d2)

# Display Original DataFrames
print("Created DataFrame 1:\n",df1,"\n")
print("Created DataFrame 2:\n",df2,"\n")

# Merging two DataFrames
df1 = df1.merge(df2, left_on='Brand',right_on='Brand_name').reindex(columns=['id', 'Brand', 'Product', 'Warehouse'])

# Display result
print("Result:\n",df1)

Output

The output of the above program is:

Example: Mapping columns from one dataframe to another

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.