Leon Rai
Leon Rai

Reputation: 1631

pandas: merge two data frames in a special order

I have checked all the other answers, I couldn't find what I was looking for.

I have a data frame df1:

0 A B
1 a good
2 b bad
3 c fair

and data frame df2:

0 C D
1 a a
2 a b
3 b c
4 a d

I want the result to be:

0 C B1   D B2
1 a good a good
2 a good b bad
3 b bad  c fair
4 a good d ---

Say, df1 plays the role of a 'dictionary', I need to extract the corresponding values of B for A elements. Note that since the element d is not defined in the df1, corresponding value is '---' in df2.

Seems so simple but can't make it work. Thanks for all the tips.

Upvotes: 2

Views: 49

Answers (1)

anky
anky

Reputation: 75080

Using s.map()

d=dict(zip(df1.A,df1.B))

df2['B1']=df2.C.map(d).fillna('---')
df2['B2']=df2.D.map(d).fillna('---')

df2=df2[['C','B1','D','B2']]

print(df2)


   C    B1  D    B2
0  a  good  a  good
1  a  good  b   bad
2  b   bad  c  fair
3  a  good  d   ---

For creating a dynamic mapping if there are more columns in df2:

my_list=[]
for i in df2.columns:
    my_list.append(df2[i].map(d).fillna('---'))
df_new=df2.join(pd.concat(my_list,axis=1),lsuffix='',rsuffix='_mapped')
print(df_new)

   C  D C_mapped D_mapped
0  a  a     good     good
1  a  b     good      bad
2  b  c      bad     fair
3  a  d     good      ---

Upvotes: 2

Related Questions