python - 将多个虚拟变量转换为一列

标签 python pandas

这个问题在这里已经有了答案:





Find the column name which has the maximum value for each row

(3 个回答)


1年前关闭。




我想转换一个看起来像这样的表:

            Blue    Green    Red
Thing 1     No      Yes      No
Thing 2     Yes     No       No
Thing 3     Yes     No       No

进入这种风格:
            Color
Thing 1     Green
Thing 2     Blue
Thing 3     Blue

在 python 或 Pandas 中有没有一个很好的方法来做到这一点?这些表格样式有名称吗?

最佳答案

只需使用 idxmax :

df.eq('Yes').idxmax(axis=1)

输出
Thing 1    Green
Thing 2     Blue
Thing 3     Blue
dtype: object

关于python - 将多个虚拟变量转换为一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184362/

相关文章:

python - 如何使用 Python 3 在 OpenCV 3 上正确加载 cv2.KeyPoint 和描述符?

python - 如果我需要获取混合类型的列怎么办?

pandas - 如何按 'pandas' 中的列获取缺失/NaN 数据的汇总计数?

python - Ubuntu 终端自动执行 python 脚本。怎么阻止呢?

python - 使用 python 中的请求循环分页 REST API

Python-属性错误: 'list' object has no attribute

python - 如何使用方法名和类名调用类的静态方法

python - 从条目具有不同长度的字典创建数据框

python - Pandas/Numpy - 填充另一列的缺失值

python - .apply 在 Pandas 中如何工作?