如何从pandas DataFrame中获取小于等于指定日期的最近datetime索引对应值
错误原因
pandas.Index.get_loc()的method参数没有previous合法取值,你需要的小于等于目标值的最近匹配对应参数为ffill(别名pad)get_loc()返回的是匹配行的整数位置,不是行对象,无法直接取列值
正确实现方法
方法1:修改原有get_loc逻辑
你的索引已经提前做了升序排序,直接调整参数和取值逻辑即可:
# 转换目标时间为和索引同时区的datetime类型,避免时区不匹配报错 target_dt = pd.to_datetime(cur_datetime, utc=True) # 获取匹配行的位置 match_pos = holdings_df.index.get_loc(target_dt, method="ffill") # 按位置取行后取holdings列 res = holdings_df.iloc[match_pos]["holdings"]
方法2:使用asof方法(更适配时序LTE查询场景)
pandas内置的asof方法专门用于返回小于等于目标时间的最后一条有效记录,代码更简洁:
target_dt = pd.to_datetime(cur_datetime, utc=True) res = holdings_df.asof(target_dt)["holdings"]
注意事项
- 两种方法都要求索引为升序排序,你现有代码中的
sort_index操作已经满足要求 - 如果目标时间早于所有索引的时间,两种方法都会返回空值,可根据业务需要补充边界校验逻辑
内容的提问来源于stack exchange,提问作者iuuujkl
相关产品推荐
相关产品推荐

