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

Pandas中如何实现列表与对应索引DataFrame列值的大小比较

错误原因

你写的代码在遍历DataFrame列表时,没有同步取出对应索引位置的Base_prices阈值,是用单个CLOSE列的数值和整个长度为19的Base_prices列表做比较,导致条件判断逻辑错误触发运行报错。

修正后代码

def Option_filtering(Option_dataframe, Base_prices):
    # 用enumerate同时获取索引和对应DataFrame,保证和Base_prices索引一一对应
    for idx, option_df in enumerate(Option_dataframe):
        # 取当前索引对应的阈值做比较
        current_base_price = Base_prices[idx]
        df_ce = option_df[(option_df.OPTION_TYPE == 'CE') & (option_df.CLOSE >= current_base_price) & (option_df.TIME <= Start_time)]
        df_ce_start_time = df_ce[df_ce.TIME == Start_time]
        df_ce_start_time = df_ce_start_time.sort_values(by=['CLOSE'])
        # 增加空判断避免无符合条件数据时iloc报错
        if df_ce_start_time.empty:
            print(f"索引{idx}无符合条件的CE数据")
            continue
        Instrument_ce = df_ce_start_time.iloc[0]    
        Strike_ce = Instrument_ce.STRIKE_PRICE
        Expiry_ce = Instrument_ce.EXPIRY
        Option_ce = Instrument_ce.OPTION_TYPE
        df_ce_strike = df_ce[df_ce.STRIKE_PRICE == Strike_ce]
        df_ce_low = df_ce_strike.LOW.min()
        print(f"索引{idx} Call Min of Low: {df_ce_low}")

Option_filtering(Option_dataframe, Base_prices)

优化说明

  • 去掉了冗余的apply(lambda x: x>=...)写法,pandas Series可以直接和单个数值做比较,运行效率更高
  • 增加了空数据判断,避免筛选结果为空时iloc[0]抛出索引越界错误
  • 输出增加索引标识,方便定位对应的数据组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:36:02