【问题标题】:How to create a dummy for every unique value in a column in python如何为python中列中的每个唯一值创建一个虚拟对象
【发布时间】:2019-05-17 11:15:54
【问题描述】:

我有一个data frame,上面有产品及其特征。

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

有什么想法吗?

【问题讨论】:

    标签: python python-3.x pandas


    【解决方案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
    

    【讨论】:

    • 感谢您合并了两种解决方案,一种用于对所有列进行转换,另一种用于对特定列进行转换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    相关资源
    最近更新 更多