首页 > 解决方案 > 如何在一列中包含多个值的 One-Hot 值

问题描述

如果记录包含值,我如何将值拆分为列并将 1 设置为记录

数据集创建

   df = pd.DataFrame({
    "date": ['1-1-2019', '1-2-2019'],
    "data": ['abc,bcd','abc,efg,hij'],
    "Others" :['Other column info','Other column info']
})

原始数据

    date       data          Others
  1-1-2019     abc,bcd       Other column info
  1-2-2019     abc,efg,hij   Other column info

预期结果

    date     abc   bcd  efg   hij   Others
   1-1-2019   1     1    0     0    Other column info
   1-2-2019   1     0    1     1    Other column info

标签: python-3.xpandasnumpyetldata-manipulation

解决方案


您可以使用数据帧 str 方法的 get_dummies 函数,如下所示

pd.concat([df, df.data.str.get_dummies(sep=",")], axis=1)

推荐阅读