ganz
ganz

Reputation: 7

Add column dataframe based on other dataframe

How to join two dataframe like this

a 1
b 2
c 2
c 5
d 3

I want to add column based on other dataframe conditional.

a io
b pk
c dea
d ak

So output would be like :

a 1 io
b 2 pk
c 2 dea
c 5 dea
d 3 ak

Upvotes: 0

Views: 52

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

You can do it using simple pd.merge(),

df3 = pd.merge(df2, df1, how='inner')

Using map(),

import pandas as pd

data_1 = {'key':['a','b','c','c','d'],'value':[1,2,2,5,3]}
data_2 = {'key':['a','b','c','d'],'value':['io','pk','dea','ak']}
df_1 = pd.DataFrame.from_dict(data_1)
df_2 = pd.DataFrame.from_dict(data_2)

dd = {k:v for k, v in zip(df_2['key'], df_2['value'])}
df_1['mapped'] = df_1['key'].map(dd)
print(df_1)

Upvotes: 1

Related Questions