如何在Python中为列中的每个唯一值创建一个虚拟变量

4

我有一个包含产品及其特征的数据框。

我希望对于每个特征列中唯一的值,创建一个新的虚拟变量。如果该特定特征值存在于该特定产品中,则该变量为1,否则为0。

例如:

import pandas as pd
df = pd.DataFrame({'id':['prod_A','prod_A','prod_B','prod_B'],
                       'color':['red','green','red','black'],
                       'size':[1,2,3,4]})

我希望您最终能得到这样一个数据框:data frame
df_f = pd.DataFrame({'id': ['prod_A', 'prod_B'],
                         'color_red': [1, 1],
                         'color_green': [1, 0],
                         'color_black': [0, 1],
                         'size_1': [1, 0],
                         'size_2': [1, 0],
                         'size_3': [0, 1],
                         'size_4': [0, 1]})

有什么想法吗?

1个回答

5
使用 get_dummies 并使用聚合函数 max:
#dummies for all columns without `id`
df = pd.get_dummies(df.set_index('id')).max(level=0).reset_index()

#dummies for columns in list
df = pd.get_dummies(df, columns=['color','size']).groupby('id', as_index=False).max()

print (df)
       id  color_black  color_green  color_red  size_1  size_2  size_3  size_4
0  prod_A            0            1          1       1       1       0       0
1  prod_B            1            0          1       0       0       1       1

1
感谢您加入了两个解决方案,一个用于对所有列进行转换,另一个用于对特定列进行转换。 - quant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接