简体   繁体   中英

Map values for categories in pandas columns based on other dataframe columns

I have two pandas dataframes.

One of them has categorized columns like this.

var1 | var2 
-----|------
A    |x
B    |y
C    |z

The other has the weight of evidence (woe) for each category present in each column of the dataframe above.

var_name | category | value
---------|----------|---------
var1     |A         |0.2
var1     |B         |0.3 
var1     |C         |0.4
var2     |x         |0.8
var2     |y         |0.9 
var2     |z         |1

I want to map the value column values to the first dataframe and get a result like the example below:

var1 | var2
-----|------
0.2  |0.8
0.3  |0.9
0.4  |1

I'm confused with applying it.

Does anyone have any tip?

Thank you so much!

We can change df2 to dict then do replace

d = df2.set_index('category').groupby('var_name').agg(dict).value.to_dict()
df1 = df1.replace(d)
Out[424]: 
   var1  var2
0   0.2   0.8
1   0.3   0.9
2   0.4   1.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM