You need to enable JavaScript to run this app. Pandas按条件查找最近datetime索引:匹配每年4月首个周日2点附近数据
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按条件查找最近datetime索引:匹配每年4月首个周日2点附近数据

实现方案
  • 第一步:预计算所有年份对应的「4月首个周日凌晨2点」目标时间点
  • 第二步:对每个目标时间,在DatetimeIndex中查找最近的索引位置
  • 第三步:校验该索引对应时间与目标时间的差值,小于15分钟则保留,否则舍弃(对应该年无符合条件的记录)

注意:请确保你的DataFrame的索引是已排序的DatetimeIndex类型,否则最近邻查找的结果会不符合预期。

实现代码如下:

import pandas as pd
from datetime import timedelta

# 先获取数据覆盖的所有年份
years = df.index.year.unique()
target_times = []

for y in years:
    # 取当年4月1日
    apr1 = pd.Timestamp(year=y, month=4, day=1)
    # 计算到第一个周日需要加的天数:周日weekday值为6
    days_to_sun = (6 - apr1.weekday()) % 7
    first_sun_apr = apr1 + timedelta(days=days_to_sun)
    # 拼接凌晨2点的目标时间
    target = first_sun_apr + timedelta(hours=2)
    target_times.append(target)

idxlist = []
# 索引排序,确保最近邻查找生效
df = df.sort_index()

for target in target_times:
    # 查找离目标时间最近的索引位置
    pos = df.index.get_indexer([target], method='nearest')[0]
    # 过滤越界的异常情况
    if pos < 0 or pos >= len(df):
        continue
    matched_time = df.index[pos]
    # 校验时间差是否小于15分钟
    if abs(matched_time - target) < timedelta(minutes=15):
        idxlist.append(df.loc[matched_time])

如果需要更高的批量处理效率,可以直接传入所有目标时间一次性查询位置,无需循环单条处理:

# 批量获取所有目标时间对应的最近位置
positions = df.index.get_indexer(target_times, method='nearest')
for i, pos in enumerate(positions):
    if pos < 0 or pos >= len(df):
        continue
    matched_time = df.index[pos]
    if abs(matched_time - target_times[i]) < timedelta(minutes=15):
        idxlist.append(df.loc[matched_time])

内容的提问来源于stack exchange,提问作者Medulla Oblongata

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 07:39:03