You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Pandas DataFrame每行第二大值对应的列名?

Pandas获取每行第二大值对应的列名

示例数据

首先定义示例DataFrame:

import pandas as pd

df = pd.DataFrame({
    'a': [4, 5, 3, 1, 2],
    'b': [20, 10, 40, 50, 30],
    'c': [25, 20, 5, 15, 10]
})

输出结果:

a   b   c
0  4  20  25
1  5  10  20
2  3  40   5
3  1  50  15
4  2  30  10

需求目标

获取每行中第二大值对应的列名,期望输出:

0    b
1    b
2    c
3    c
4    c
dtype: object

优雅实现方法

方法1:结合nlargest与idxmin

先提取每行前两大的数值,再取其中较小值(即第二大值)对应的列名:

df.apply(lambda x: x.nlargest(2).idxmin(), axis=1)

方法2:排序后提取指定位置列名

对每行数值降序排序,直接取排序后第2个元素(索引为1)的列名:

df.apply(lambda x: x.sort_values(ascending=False).index[1], axis=1)

方法3:利用rank标记排名筛选

给每行数值按降序排名,筛选出排名为2的列名:

df.rank(axis=1, ascending=False).eq(2).idxmax(axis=1)

以上三种方法均能得到符合预期的结果,可根据个人习惯选择使用。

内容的提问来源于stack exchange,提问作者Xiaokang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:00:52