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

如何在Pandas DataFrame中为每行添加第二大值列'sec_max'

为Pandas DataFrame每行生成第二大值列的方法

下面提供几种实用的方法来生成每行的第二大值列sec_max,同时也可以将该列转为列表:

方法一:使用nlargest(简洁直观)

利用Series.nlargest()获取每行前2大的值,再取第二个元素:

# 生成第二大值列
df["sec_max"] = df.apply(lambda x: x.nlargest(2).iloc[-1], axis=1)
# 转为列表
sec_maxV = df['sec_max'].tolist()

nlargest(2)会返回每行降序排列的前2个最大值,iloc[-1]提取其中的第二大值。

方法二:通过排序提取

对每行的值进行降序排序后,取索引为1的元素(即第二大值):

df["sec_max"] = df.apply(lambda x: x.sort_values(ascending=False).iloc[1], axis=1)
sec_maxV = df['sec_max'].tolist()

方法三:numpypartition(高效处理大数据集)

如果你的DataFrame数据量较大,用numpy的partition方法效率更高,避免apply的性能瓶颈:

import numpy as np

df["sec_max"] = np.partition(df.values, -2, axis=1)[:, -2]
sec_maxV = df['sec_max'].tolist()

np.partition会将每行数据按大小分区,-2表示定位到第二大值的位置,直接提取即可,运算速度远快于前两种方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 02:32:06