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

基于最小索引从Pandas DataFrame提取指定条件的价格值

解决方法:提取符合条件的最小索引对应的Price值

没问题,我来帮你搞定这个需求!下面是几种基于Pandas(也包含NumPy方案)的可行方法,都能准确拿到你要的结果:

先构造示例DataFrame(方便你测试)

首先我们先模拟你提到的场景,创建一个和你示例匹配的DataFrame:

import pandas as pd

df = pd.DataFrame({
    'c_h': ['spam', 'ham', 'ham', 'ham'],
    'qual': ['good', 'good', 'bad', 'bad'],
    'price': [5.0, 8.0, 11.0, 15.0]
})

方法1:Pandas布尔筛选 + 最小索引提取

这是最直观的方法,分三步完成:

  1. 用布尔条件筛选出所有符合c_h=='ham'且qual=='bad'的行
  2. 从筛选结果中找出最小的索引
  3. 根据索引提取对应的price值

代码如下:

# 筛选符合条件的行
filtered_rows = df[(df['c_h'] == 'ham') & (df['qual'] == 'bad')]

# 一定要先检查是否有匹配的行,避免空值报错
if not filtered_rows.empty:
    min_index = filtered_rows.index.min()
    target_price = df.loc[min_index, 'price']
    print(target_price)  # 输出:11.0
else:
    print("⚠️ 没有找到符合条件的行")

方法2:链式写法(更简洁)

如果想少写几行代码,可以把筛选和取索引的操作链式完成,记得同样加上空值判断:

condition = (df['c_h'] == 'ham') & (df['qual'] == 'bad')
matching_indices = df[condition].index

if not matching_indices.empty:
    target_price = df.loc[matching_indices.min(), 'price']
    print(target_price)
else:
    print("⚠️ 没有找到符合条件的行")

方法3:用NumPy实现

如果你习惯用NumPy,也可以通过布尔数组找到匹配的索引,再取最小值:

import numpy as np

# 将DataFrame的列转为NumPy数组,生成布尔条件
condition = (df['c_h'].values == 'ham') & (df['qual'].values == 'bad')
# 获取所有符合条件的索引
matching_indices = np.where(condition)[0]

if len(matching_indices) > 0:
    min_index = matching_indices.min()
    target_price = df.loc[min_index, 'price']
    print(target_price)
else:
    print("⚠️ 没有找到符合条件的行")

关键注意点

  • 布尔条件中要用**&**而不是and,因为我们需要对DataFrame的每一行做元素级的判断
  • 必须添加空值检查:如果没有任何行符合条件,直接调用index.min()会抛出错误,所以一定要先判断筛选结果是否为空

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 06:55:37