python - 如何选择数值最大的列名作为新的列元素?

标签 python pandas dataframe

我有一个名为a的DataFrame,如下所示。

import pandas as pd 
a=pd.DataFrame({'id':[1,2,3],'label 0':[0.2,0.4,0.5],
'label 1':[0.3,0.2,0.1],'label 2':[0.5,0.4,0.4]})

输入:

    id  label 0  label 1  label 2
0   1     0.2     0.3     0.5
1   2     0.4     0.2     0.4
2   3     0.5     0.1     0.4

每一行包含每个id属于三个标签的概率,其中三个标签是label 0label 1标签2。我现在想使用概率最高的label(列名)作为id的预测值。如果有两个概率最高的标签,则取其中之一。

预期:

    id   predict  
0   1    label 2     
1   2    label 0     
2   3    label 0 

提前致谢!

最佳答案

使用idxmax对于每一行(即 axis=1):

a.drop('id', 1).idxmax(1)

#0    label 2
#1    label 0
#2    label 0

concatid 列:

pd.concat([a.id, a.drop('id', 1).idxmax(1).rename('predict')], 1)

#   id  predict
#0   1  label 2
#1   2  label 0
#2   3  label 0

关于python - 如何选择数值最大的列名作为新的列元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52397468/

相关文章:

python - 根据三列中的匹配值将多个数据框合并为单个数据框

python - pandas 有条件滚动平均值

python - 将 pandas 数据帧行拆分为搜索到的列值到新的数据帧中

python - 尝试使路径工作 - 尝试超越顶级包的相对导入

python / Pandas : How to Match List of Strings with a DataFrame column

python - 如何在 Pandas 中打印 CSV 中的某些行

python - 如何使用分组依据并返回具有空值的行

使用 __init__.py 导入 Python 子模块

python - DRF 不会将原始 JSON 字符串发送到浏览器。它返回一个 JSON 字符串,想要绕过调用 json.load

python - 如何让 CGI 脚本在 MacOS 10.10 Yosemite 上工作