【问题标题】:Performing one hot encoding on dataframe with multiple groups对具有多个组的数据帧执行一次热编码
【发布时间】:2021-08-10 14:03:54
【问题描述】:

我是在 python 中的数据集上学习机器学习的新手,我正在尝试对以下数据帧执行一次热编码(仅显示一个 sn-p)

id country device
100 sg samsung
100 ch galaxy s
200 ab pocophone
200 ee iphone 1
200 my iphone 2

我希望结果是这样的

id sg ch ab ee my
100 1 1 0 0 0
200 0 0 1 1 1

不胜感激任何建议和帮助,谢谢大家!

【问题讨论】:

    标签: python dataframe one-hot-encoding


    【解决方案1】:

    使用pd.crosstab:

    >>> pd.crosstab(df['id'], df['country'])[df['country']
    country  sg  ch  ab  ee  my
    id
    100       1   1   0   0   0
    200       0   0   1   1   1
    

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2020-10-06
      • 2018-01-04
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多