将 one_hot_encoding 0/1 替换为其他列中的值

Replace one_hot_encoding 0/1 with values from other column

我有一个包含重复用户交易的数据框。我想汇总我的数据并为每个用户构建一个包含一行的数据框。

原始数据框如下所示:

id       usage     country    publisher      type_status
123      6.77         US          X          bookstore_declined
123      4.25         US          X          super_approved
123      88.7         US          X          bookstore_approved
123      5.6          US          X          pharmacies_approved
456      43.66        BZ          Y          pharmacies_approved
456      56.87        BZ          Y          super_approved
456      9.65         BZ          Y          bookstore_approved

我想在 type_status 功能上使用 one_hot_encoding,但我希望在新的虚拟列中使用 one_hot_encoding 而不是 0/1,新列将具有 'usage' 值。

这是我正在寻找的示例:

id   country  publisher     bookstore_declined  super_approved  bookstore_approved   
123    US        X            6.77                4.25             88.7
456    BZ        Y             0                  56.87            9.65

这是我的代码: 如何用使用值替换 0/1?

df=pd.get_dummies(df,columns=['type_status'],drop_first=True)

嗨,我初始化了数据,所以我也得到了一个数据帧

import pandas as pd

test_df = {
    'id': [123,123,123,123,456,456,456],
    'usage' :[6.77,4.25,88.7,5.6,43.66,56.87,9.65],
    'country' : ['US','US','US','US','BZ','BZ','BZ'],
    'publisher' : ['x','x','x','x', 'y','y','y'],
    'type_status': ['bookstore_declined','super_approved','bookstore_approved','pharmacies_approved','pharmacies_approved', 'super_approved','bookstore_approved']
}

df = pd.DataFrame(test_df)

df=pd.get_dummies(df,columns=['type_status'],drop_first=True)

结果看起来像你的

    id  usage country publisher  type_status_bookstore_declined  ...
0  123   6.77      US         x                               1   
1  123   4.25      US         x                               0   
2  123  88.70      US         x                               0   

根据这个Whosebug answer你可以用下面的命令将多个列相乘:

df.update(df.iloc[:, 4:7].mul(df.usage, 0))

删除用法列:

df = df.drop('usage', axis=1)

结果如下所示:

id  country     publisher   type_status_bookstore_declined  type_status_pharmacies_approved     type_status_super_approved
0   123     US  x   6.77    0.00    0.00
1   123     US  x   0.00    0.00    4.25
2   123     US  x   0.00    0.00    0.00
3   123     US  x   0.00    5.60    0.00
4   456     BZ  y   0.00    43.66   0.00
5   456     BZ  y   0.00    0.00    56.87
6   456     BZ  y   0.00    0.00    0.00