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

如何无需使用.to_list()[0]从(1,1)型pandas DataFrame提取单个值?

从pandas DataFrame提取单个值的更优方法

针对你提到的从过滤后的DataFrame/Series中提取单个值的需求,有几种比.to_list()[0]更简洁、高效的方法:

方法1:使用.iloc[0]

直接通过位置索引获取Series的第一个元素,写法简洁,适合明确结果只有单个元素的场景:

# 分步写法
row_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]
column_and_row_of_interest = row_of_interest['col3']
value_of_interest = column_and_row_of_interest.iloc[0]

# 合并写法
value_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]['col3'].iloc[0]

方法2:使用.values[0]

提取Series的numpy数组表示,再取第一个元素,性能表现不错:

value_of_interest = column_and_row_of_interest.values[0]

# 合并写法
value_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11)]['col3'].values[0]

方法3:使用.item()

这是专门为单个元素设计的方法,安全性更高——如果过滤后结果不是单个元素(比如意外得到多行),会直接抛出错误,避免隐式的索引问题;同时返回原生Python类型(如int/float),而非numpy类型:

value_of_interest = column_and_row_of_interest.item()

# 合并写法
value_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11), 'col3'].item()

额外优化:直接在loc中指定列

你可以把列名直接放在loc的第二个参数里,省去单独取列的步骤,代码更紧凑:

value_of_interest = df.loc[(df['col1'] == 'a') & (df['col2'] > 11), 'col3'].item()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:50:16