python - 返回对应于行中最大值的列标题

标签 python pandas dataframe max

我有一个如下所示的数据框:

case    inc_date    is1     is5     is10    im1     im5     im10
686     6/8/1972    0.141   0.300   0.149   0.134   0.135   0.142
950     6/1/1945    0.160   0.345   0.172   0.088   0.096   0.138
1005    10/16/1945  0.164   0.261   0.151   0.131   0.261   0.133
1005    11/12/1947  0.146   0.310   0.182   0.112   0.129   0.121
1180    10/9/1945   0.159   0.278   0.134   0.141   0.138   0.150

我想找出每行中的最大值,并返回值为最大值的列名。例如,对于上面的数据框,它会返回:

686 is5
950 is5
1005 is5, im5
1005 is5
1180 is5

最佳答案

您可以使用 idxmax使用 axis=1 查找每行中具有最大值的列:

1 is5
2 is5
3 is5
4 is5
5 is5

要创建新列“Max”,请使用 df['Max'] = df.idxmax(axis=1)

要查找每列中出现最大值的行索引,请使用 df.idxmax()(或等效的 df.idxmax(axis=0)) .


对于第二高,你可以使用 df.apply(lambda x: df.index[x.argsort()[::-1][1]], axis=1)

关于python - 返回对应于行中最大值的列标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47637696/

相关文章:

python - 减少 pandas DataFrame 中的列数

python - 太空射击游戏有轻微错误

python - Django 管理 - 外键 "field object"列表

python - Flask_httpauth 装饰器缺少所需的位置参数 f

python - Python 中的 InfluxDB 和 pandas 错误

Python 数据帧 : find previous row's value before a specific value with same value in other columns

python - 如何使用 Jupyter Notebook 进行打印

python - 如何在 Pandas 中实现 dtype 转换器功能?

python - 值错误 : Mixing dicts with non-Series may lead to ambiguous ordering

Python/Pandas 与 NaN 数据合并问题