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
  Running search/replace across Polars dataframe columns efficiently hobbycoder 3 4,283 Oct-28-2024, 03:18 AM
Last Post: hobbycoder
  Converting a json file to a dataframe with rows and columns eyavuz21 13 20,261 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 2,563 Sep-08-2022, 06:32 AM
Last Post: klllmmm
  Nested for loops: Iterating over columns of a DataFrame to plot on subplots dm222 0 3,520 Aug-19-2022, 11:07 AM
Last Post: dm222
  Remove if similar values available based on two columns klllmmm 1 2,562 Feb-20-2022, 06:55 PM
Last Post: Larz60+
  Apply fillna to multiple columns in dataframe rraillon 2 5,137 Aug-05-2021, 01:11 PM
Last Post: rraillon
  How to rename dataframe columns based on the content in an index? ar_mahdavi 2 3,789 Jun-07-2021, 06:09 AM
Last Post: ricslato
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 6,557 Mar-09-2021, 12:24 PM
Last Post: KMV
  How to sum across variable columns in a dataframe rennerom 2 5,293 Jan-31-2021, 05:44 PM
Last Post: rennerom
  How to split dataframe object rows to columns Mekala 1 4,626 Nov-12-2020, 04:18 PM
Last Post: michael1789

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.