Python 用另一列中的值替换一个\u热\u编码0/1

Python 用另一列中的值替换一个\u热\u编码0/1,python,one-hot-encoding,Python,One Hot Encoding,我有一个重复用户交易的数据框架。我希望聚合数据,并为每个用户构建一个包含一行的数据框 原始数据帧如下所示: id usage country publisher type_status 123 6.77 US X bookstore_declined 123 4.25 US X super_approved 123 88.7

我有一个重复用户交易的数据框架。我希望聚合数据,并为每个用户构建一个包含一行的数据框

原始数据帧如下所示:

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_编码,但我希望在新的伪列中,新列将具有“usage”值,而不是0/1

下面是我要找的一个例子:

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   
根据这一点,您可以使用以下命令将多个列相乘:

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

试试这个
df=pd.get\u dummies(df.type\u status,drop\u first=True)
它不起作用,因为我需要“用法”列的值。而且,我只得到dummies列,而不是所有的数据帧。