如果值=1(二进制值),则提取列名并将它们与分隔符组合并将其放入新列中

我有一个带有二进制值的数据框,在使用 Pandas 执行 get_dummies 后

df= 
Values  A1  A2  B1  B2  B3  B4  C1  C2  C3
10      1   0   1   0   0   0   1   0   0
12      0   1   0   0   1   0   0   1   0
3       0   1   0   1   0   0   0   0   1
5       1   0   0   0   0   1   1   0   0

我想要一个新列,它包含所有列的组合,其中包含 1

Expected output:

Values  A1  A2  B1  B2  B3  B4  C1  C2  C3  Combination
10      1   0   1   0   0   0   1   0   0   A1~~B1~~C1
12      0   1   0   0   1   0   0   1   0   A2~~B3~~C2
3       0   1   0   1   0   0   0   0   1   A2~~B2~~C3
5       1   0   0   0   0   1   1   0   0   A1~~B4~~C3

实际矩阵可以是25000+行*1000+列

在 R 中有一个类似的解决方案,但我在 Python 中需要它 bcoz 所有其他依赖项都在 python 中,而 R 对我来说是新的。

提取二进制矩阵中值为 1 的列名

Codes in R below, & need similar one or any other code in python which can help me to arrive at my expected output
Solution 1 : 
as.matrix(apply(m==1,1,function(a) paste0(colnames(m)[a], collapse = "")))

Solution 2: 
t <- which(m==1, arr.ind = TRUE)
as.matrix(aggregate(col~row, cbind(row=rownames(t), col=t[,2]), function(x) 
                                                    paste0(colnames(m)[x], collapse = "")))

类似的东西怎么可能达到我在 Python 中的预期输出?

回答

df["Combination"] = df.iloc[:, 1:].dot(df.add_suffix("~~").columns[1:]).str[:-2]

我们选择除Valueswith之外的列iloc,然后形成一个点积,其中第二个操作数是添加到末尾的dfwith 的相应列~~。结果也给出~~了最后,所以我们用.str[:-2]

要得到

   Values  A1  A2  B1  B2  B3  B4  C1  C2  C3 Combination
0      10   1   0   1   0   0   0   1   0   0  A1~~B1~~C1
1      12   0   1   0   0   1   0   0   1   0  A2~~B3~~C2
2       3   0   1   0   1   0   0   0   0   1  A2~~B2~~C3
3       5   1   0   0   0   0   1   1   0   0  A1~~B4~~C1


以上是如果值=1(二进制值),则提取列名并将它们与分隔符组合并将其放入新列中的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>