Python Forum
How to map dataframe based on two columns
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to map dataframe based on two columns
#1
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('')
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Converting a json file to a dataframe with rows and columns eyavuz21 13 4,405 Jan-29-2023, 03:59 PM
Last Post: eyavuz21
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 828 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 1,706 Aug-19-2022, 11:07 AM
Last Post: dm222
  Remove if similar values available based on two columns klllmmm 1 1,354 Feb-20-2022, 06:55 PM
Last Post: Larz60+
  Apply fillna to multiple columns in dataframe rraillon 2 2,427 Aug-05-2021, 01:11 PM
Last Post: rraillon
  How to rename dataframe columns based on the content in an index? ar_mahdavi 2 2,470 Jun-07-2021, 06:09 AM
Last Post: ricslato
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 3,487 Mar-09-2021, 12:24 PM
Last Post: KMV
  How to sum across variable columns in a dataframe rennerom 2 2,751 Jan-31-2021, 05:44 PM
Last Post: rennerom
  How to split dataframe object rows to columns Mekala 1 2,496 Nov-12-2020, 04:18 PM
Last Post: michael1789
  convert list to five columns dataframe in sequence tonycat 2 2,475 Sep-29-2020, 06:47 AM
Last Post: tonycat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020