【问题标题】:How to convert a data frame to one hot encoded如何将数据帧转换为热编码
【发布时间】:2017-09-21 21:50:15
【问题描述】:

我有一个数据框,其中 id 可以有多种事件类型

> head(eventtype, 10)
      id    event_type
1   6597 event_type 11
2   8011 event_type 15
3   2597 event_type 15
4   5022 event_type 15
5   5022 event_type 11
6   6852 event_type 11
7   6852 event_type 15
8   5611 event_type 15
9  14838 event_type 15
10 14838 event_type 11

我想转成格式

   id event_type 1 event_type 2 event_type 3 ... event_type 50 
14838            0            0            0 ...             0 

在 R 中实现这一目标的最佳方法是什么?有包吗? 我尝试过使用假人:

new_my_data

但它不起作用。我也尝试搜索,但可以找到解决此特定问题的方法。几乎所有的帖子都假设一种热编码是众所周知的。

请帮忙。

【问题讨论】:

标签: r dataframe one-hot-encoding


【解决方案1】:

mltoolsdata.table 很容易:

> result
       id event_type_event_type 10 event_type_event_type 11 event_type_event_type 12 event_type_event_type 13 event_type_event_type 14
  1: 1274                        0                        0                        0                        0                        0
  2: 7668                        0                        0                        0                        0                        1
  3:  545                        1                        0                        0                        0                        0
  4: 5614                        0                        0                        0                        0                        0
  5: 9376                        0                        0                        0                        0                        0

代码

set.seed(1701)
df <- data.frame(id = sample(1:10000, 500, replace = TRUE),
                 event_type = paste("event_type", sample(10:20, 500, replace = TRUE)))
dt <- as.data.table(df)
result <- one_hot(dt)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    • 2019-09-06
    • 2021-12-21
    • 2016-12-04
    • 1970-01-01
    • 2017-05-14
    相关资源
    最近更新 更多