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

问题描述

我有一个与重复用户进行交易的数据框。我想汇总我的数据,并为每个用户建立一个带有一行的数据框。

原始数据框如下所示:

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,但我希望在新的虚拟列中使用0代替而不是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,456,456],'usage' :[6.77,4.25,88.7,5.6,43.66,56.87,9.65],'country' : ['US','US','BZ','BZ'],'publisher' : ['x','x','y','y'],'type_status': ['bookstore_declined','super_approved','bookstore_approved','pharmacies_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   

根据此Stackoverflow 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