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

Python循环访问pandas日期索引报KeyError如何自动取前一日期数据

解决方案

你可以通过封装一个自动回退查找有效日期的工具函数实现需求,不用重复写判断逻辑,具体修改步骤如下:

  • 第一步:先在循环外定义一个安全取值的工具函数,实现「日期不存在就自动取前一天数值」的逻辑
import pandas as pd

def get_sp1500_price(date_str, sp_df):
    col = 'S&P 1500 SUPER COMPOSITE - PRICE INDEX'
    current_date = pd.Timestamp(date_str)
    while True:
        check_date_str = current_date.strftime("%Y-%m-%d")
        # 检查当前日期是否在数据集索引中
        if check_date_str in sp_df.index:
            return sp_df.loc[check_date_str, col]
        # 不存在则减1天继续查找
        current_date -= pd.Timedelta(days=1)
        # 可选增加边界校验,防止极端情况死循环
        # if current_date < pd.Timestamp(sp_df.index.min()):
        #     raise Exception(f"已回退到数据集最早日期{sp_df.index.min()},仍无对应数据")
  • 第二步:替换你原来else分支里的计算代码,把两个直接.loc取值的部分替换为调用上面的函数即可

原来的计算行:

Portfolio_1_4 = Portfolio_1_4 * SP1500DailyReturns.loc[n_short, 'S&P 1500 SUPER COMPOSITE - PRICE INDEX'] / SP1500DailyReturns.loc[Portfolio_1_4_Date_sell_short, 'S&P 1500 SUPER COMPOSITE - PRICE INDEX']

替换为:

# 安全获取两个日期对应的指数值
current_price = get_sp1500_price(n_short, SP1500DailyReturns)
sell_price = get_sp1500_price(Portfolio_1_4_Date_sell_short, SP1500DailyReturns)
# 执行计算
Portfolio_1_4 = Portfolio_1_4 * current_price / sell_price

注意事项

如果你的SP1500DailyReturns数据集的索引本身是Timestamp类型而非字符串类型,可直接删除函数中日期转字符串的步骤,直接判断current_date in sp_df.index即可,运行效率更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:57:01