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

如何筛选索引处于指定日期区间内的DataFrame数据?

解决方法

你的问题出在直接用整列做比较时,pandas的广播逻辑没法正确匹配多组日期区间和df_dec_light的索引。下面是几种靠谱的实现方式:

方法1:用区间索引(IntervalIndex)快速匹配

先把df_rally的rally_start和rally_end转换成区间对象,再检查索引是否落在任意区间内:

# 创建区间索引,closed='both'表示包含两端日期
rally_intervals = pd.IntervalIndex.from_arrays(
    df_rally['rally_start'], 
    df_rally['rally_end'], 
    closed='both'
)
# 筛选出索引在任意区间内的行
filtered_df = df_dec_light[df_dec_light.index.isin(rally_intervals)]

方法2:生成掩码逐行匹配

遍历df_rally的每个区间,生成对应的布尔掩码,最后取所有掩码的逻辑或:

# 初始化全False的掩码
mask = pd.Series(False, index=df_dec_light.index)
# 遍历每个区间更新掩码
for _, row in df_rally.iterrows():
    mask |= (df_dec_light.index >= row['rally_start']) & (df_dec_light.index <= row['rally_end'])
# 应用掩码筛选
filtered_df = df_dec_light[mask]

方法3:展开区间为日期集合再匹配

如果你的日期区间跨度不大,可以把所有区间内的日期提取成集合,再用isin筛选:

# 生成所有区间内的日期集合
rally_dates = set()
for _, row in df_rally.iterrows():
    # 生成该区间内的所有日期,freq根据你的日期粒度调整,比如'D'是天
    dates_in_range = pd.date_range(row['rally_start'], row['rally_end'], freq='D')
    rally_dates.update(dates_in_range)
# 筛选索引在集合内的行
filtered_df = df_dec_light[df_dec_light.index.isin(rally_dates)]

这几种方法都能解决你原来的维度不匹配问题,根据你的数据量和日期粒度选合适的就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:10:25