python - 在 Pandas 中反转 'one-hot' 编码

标签 python pandas dataframe

我想从这个基本上是一个热编码的数据帧开始。

 In [2]: pd.DataFrame({"monkey":[0,1,0],"rabbit":[1,0,0],"fox":[0,0,1]})

    Out[2]:
       fox  monkey  rabbit
    0    0       0       1
    1    0       1       0
    2    1       0       0
    3    0       0       0
    4    0       0       0

到这个是“反向”单热编码的。

    In [3]: pd.DataFrame({"animal":["monkey","rabbit","fox"]})
    Out[3]:
       animal
    0  monkey
    1  rabbit
    2     fox

我想有一些巧妙地使用 apply 或 zip 来做瘦,但我不确定如何......有人可以帮忙吗?

我使用索引等尝试解决这个问题并没有取得多大成功。

最佳答案

更新: 我认为 ayhan是对的,应该是:

df.idxmax(axis=1)

演示:

In [40]: s = pd.Series(['dog', 'cat', 'dog', 'bird', 'fox', 'dog'])

In [41]: s
Out[41]:
0     dog
1     cat
2     dog
3    bird
4     fox
5     dog
dtype: object

In [42]: pd.get_dummies(s)
Out[42]:
   bird  cat  dog  fox
0   0.0  0.0  1.0  0.0
1   0.0  1.0  0.0  0.0
2   0.0  0.0  1.0  0.0
3   1.0  0.0  0.0  0.0
4   0.0  0.0  0.0  1.0
5   0.0  0.0  1.0  0.0

In [43]: pd.get_dummies(s).idxmax(1)
Out[43]:
0     dog
1     cat
2     dog
3    bird
4     fox
5     dog
dtype: object

旧答案:(很可能是错误答案)

试试这个:

In [504]: df.idxmax().reset_index().rename(columns={'index':'animal', 0:'idx'})
Out[504]:
   animal  idx
0     fox    2
1  monkey    1
2  rabbit    0

数据:

In [505]: df
Out[505]:
   fox  monkey  rabbit
0    0       0       1
1    0       1       0
2    1       0       0
3    0       0       0
4    0       0       0

关于python - 在 Pandas 中反转 'one-hot' 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38334296/

相关文章:

python - 如何在 Python 中为矩阵/嵌套列表的每个元素加 1?

python - Scrapy 合约具有多种解析方法

r - 创建一个新列作为列表返回

r - 跨列和条件按行求和

python - 如何为 Pandas 数据框的每一行的列分配一个值?

python - 在 python 中删除 span 标签

python - 连接 Pandas 日期时间

python - Pandas:将各种相似的子字符串映射到单一标准格式

Python Pandas - 计算总均值,按字段分组,然后计算分组均值并追加

python - 一列中每次出现的值在另一列中的总和