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

如何按行和列比较DataFrame中列表的第二个元素?

如何按列/行比较DataFrame中列表的第二个元素并取最大值?

示例DataFrame

Col1         col2          col3
['A',0.2,5]  ['A',0.4,5]  ['A',0,5]
['A',0.4,5]  ['A',0.2,5]  ['A',0.7,5]
['A',0.1,5]  ['A',0.1,5]  ['A',0.20,5]
['A',0.25,5] ['A',0.9,5]  ['A',0.22,5]

按列取第二个元素的最大值

通过apply遍历每一列,提取列表的第二个元素(索引为1)后取最大值:

import pandas as pd

# 构造示例DataFrame
data = {
    'Col1': [['A',0.2,5], ['A',0.4,5], ['A',0.1,5], ['A',0.25,5]],
    'col2': [['A',0.4,5], ['A',0.2,5], ['A',0.1,5], ['A',0.9,5]],
    'col3': [['A',0,5], ['A',0.7,5], ['A',0.20,5], ['A',0.22,5]]
}
df = pd.DataFrame(data)

# 计算列最大值
col_max = df.apply(lambda col: col.str[1].max())
print(col_max)

输出结果:

Col1    0.4
col2    0.9
col3    0.22
dtype: float64

按行取第二个元素的最大值

通过apply指定axis=1遍历每一行,提取每个列表的第二个元素后取最大值:

# 计算行最大值
row_max = df.apply(lambda row: max(lst[1] for lst in row), axis=1)
print(row_max)

输出结果:

0    0.2
1    0.7
2    0.2
3    0.9
dtype: float64

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 12:25:20