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

Python pandas条件匹配目标行时如何同时获取多个字段值

问题描述

现有数据与代码如下:

prices_df = [1106, 1098, 1090.625, 1082.577, 1074.52]
future_dates = {'Date': ['2022-05-02', '2022-05-03', '2022-05-04', '2022-05-05', '2022-05-06'],
                'High': [1020, 1005, 966, 2100, 2000],
                }

future_prices = pd.DataFrame(future_dates)
future_prices = future_prices.set_index('Date')

df3.loc[i, 'Break_date'] = (future_dates.High > prices_df).idxmax() if any(future_dates.High > prices_df) else 0

原有代码逻辑为返回future_dates中High值高于prices_df对应位置值的日期。现在需要新增Break_price列,存入匹配到的对应High值,最终拿到满足条件行的Date、High两个字段,补全以下代码:

df3.loc[i, 'Break_price'] = ???
实现方法

推荐先把判断条件抽为变量,避免重复计算,逻辑更清晰:

# 生成匹配条件的布尔序列
break_mask = future_prices['High'] > prices_df
if break_mask.any():
    first_break_date = break_mask.idxmax()
    df3.loc[i, 'Break_date'] = first_break_date
    # 通过匹配到的日期索引取对应High值
    df3.loc[i, 'Break_price'] = future_prices.loc[first_break_date, 'High']
else:
    # 无匹配时赋值默认值
    df3.loc[i, 'Break_date'] = 0
    df3.loc[i, 'Break_price'] = 0

如果需要保持和原有代码一致的单行写法,也可以直接写为:

df3.loc[i, 'Break_price'] = future_prices.loc[(future_prices['High'] > prices_df).idxmax(), 'High'] if (future_prices['High'] > prices_df).any() else 0

说明:原代码中直接调用future_dates.High属于不规范写法,future_dates是原生字典,不存在.High属性,既然已经构建了future_prices这个DataFrame,统一从DataFrame中取列即可避免报错。

用给出的测试数据运行后,第一个满足条件的是2022-05-05对应的行,最终Break_date为2022-05-05,Break_price为2100,结果符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:36:35