如何将一个单元格中的多个值拆分为几个用布尔值标记的要素列?(R/Python)

2024-06-16 13:14:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.cvs数据集,它有一列有多个值。 我希望我可以将这些值拆分,并将它们更改为带有布尔标记的单个功能列,以便在特定项具有此功能时使用 e、 g.:

| year_built |        amenity                      |
----------------------------------------------------
|       1990 |    Courtyard,                       |
|       2015 |    Elevator,Pets - Cats ok,         |
|       1998 |    Elevator,Pets - Cats ok,Post-War |

转移到

|  year_built |             amenity              |  Elevator | Pets - Cats ok | Post-War | Courtyard |  
------------------------------------------------------------------------------------------------------
|        1990 | Courtyard,                       |         0 |              0 |        0 |         1 |  
|        2015 | Elevator,Pets - Cats ok,         |         1 |              1 |        0 |         0 |  
|        1998 | Elevator,Pets - Cats ok,Post-War |         1 |              1 |        1 |         0 |  

我检查了预处理包中的scikit学习类'binarizer',它可以实现我想要的,但在此之前,我还需要一些方法来帮助分割这些值并识别它们。你知道吗

有没有什么方法可以使用R或Python来处理这个问题?你知道吗


Tags: 数据方法标记功能okpostyearcvs
1条回答
网友
1楼 · 发布于 2024-06-16 13:14:07

我用一个假数据集演示了一种方法。你知道吗

set.seed(123)
d <- lapply(replicate(10, sample(letters[1:10], sample(1:10, 1))), function(x){
  paste(x, collapse = ",")
})
d <- data.frame(id = 1:10, features = unlist(d), stringsAsFactors = FALSE)
d
#    id            features
# 1   1               h,d,j
# 2   2 a,e,h,d,c,i,b,f,g,j
# 3   3   c,a,j,g,f,d,h,e,b
# 4   4     f,j,c,b,i,e,h,d
# 5   5                   e
# 6   6     c,j,b,a,i,f,h,g
# 7   7                 c,e
# 8   8               i,a,d
# 9   9     b,f,j,a,e,i,h,d
# 10 10                   d

使用逗号拆分特征,并恢复唯一特征向量:

d$split <- strsplit(d$features, ",")
features <- unique(unlist(d$split))
features
# [1] "h" "d" "j" "a" "e" "c" "i" "b" "f" "g"

我们使用%in%操作符检查是否在每个观察的特征集中找到了特征:

features_matrix <- do.call(rbind, lapply(d$split, function(x) features %in% x))
features_matrix <- as.data.frame(features_matrix)
dimnames(features_matrix) <- list(d$id, features)
features_matrix
#        h     d     j     a     e     c     i     b     f     g
# 1   TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
# 2   TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
# 3   TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE
# 4   TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
# 5  FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
# 6   TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
# 7  FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE
# 8  FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE
# 9   TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE
# 10 FALSE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE

相关问题 更多 >