s_khan92
s_khan92

Reputation: 979

How to map 2 columns by using 2 dataframe in pandas?

df_map

Camp_old     Camp_New         Plat
A_B          C_D              Car
E_F          G_H              Auto
W_X          Y_Z              Star


df_main
Camp        Num        
W_X         5
E_F         NaN
A_C_R       3
A_B         6

I want to map the new camp into Camp of df_main which is easy by creating the dictionary and pass it to map. My challenge is that I need to map Plat from df_map as well as new column.

This is how my desired output should be:

    Camp        Num     Camp_New    Plat
    W_X         5       Y_Z         Star
    E_F         NaN     G_H         Auto
    A_C_R       3       NaN         NaN
    A_B         6       C_D         Car

Upvotes: 1

Views: 70

Answers (1)

ThePyGuy
ThePyGuy

Reputation: 18406

You need to merge both the dataframe:

>>> df_main.merge(df_map, left_on='Camp', right_on='Camp_old', how='left')

    Camp  Num Camp_old Camp_New  Plat
0    W_X  5.0      W_X      Y_Z  Star
1    E_F  NaN      E_F      G_H  Auto
2  A_C_R  3.0      NaN      NaN   NaN
3    A_B  6.0      A_B      C_D   Car

Upvotes: 1

Related Questions