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
相关产品推荐
相关产品推荐

