Python Forum

Full Version: How to map dataframe based on two columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have two dataframes,

df1:

Name	Pop	RANK Indian	333	1 USA 42	56 Taiwan	688	3 Hsinchu	34	54 Indian	333	28 Taiwan	688	23
df2:

Name	CAP Pop	RANK Indian	NDL 333	1 USA WDC 42	56 Taiwan	TPE 688	3 Hsinchu	Zubei 34	54 Indian	NDL 222	28
I want to map Name & RANK in df1 to df2, and get CAP from df2. I could only use one column mapping, but I could not be able to map based on two columns. I use below code,


df1['CAP'] = df1['Name','RANK'].map(df2.set_index(['Name','RANK'])['CAP']).fillna('')