我有一个data frame,上面有行的product及其特征。

我想为每个特征列中的每个唯一值创建一个新的虚拟变量,如果该特定product的特定特征值存在,则该虚拟变量将为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]})

有任何想法吗 ?

分析解答

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