You need to enable JavaScript to run this app. Python Pandas日期匹配无结果时获取最近前置日期行索引的实现方案
优惠活动
大模型
产品
解决方案
定价
更多

Python Pandas日期匹配无结果时获取最近前置日期行索引的实现方案

Pandas日期匹配索引获取解决方案

你原来的代码问题在于固定偏移6个月的逻辑无法适配不同输入日期和最近前置日期的动态间隔,直接从现有数据集筛选符合条件的日期即可实现需求,无需手动计算偏移量。

通用实现代码(易理解,适合中小数据量)

import pandas as pd

# 提前将Date列转为datetime格式,仅需执行一次,无需每次查询重复转换
df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)

def get_target_index(input_date_str):
    input_date = pd.to_datetime(input_date_str, dayfirst=True)
    # 优先查询完全匹配的日期
    exact_match = df[df['Date'] == input_date]
    if not exact_match.empty:
        return exact_match.index
    # 无完全匹配时筛选所有小于输入日期的记录
    prev_records = df[df['Date'] < input_date]
    if prev_records.empty:
        # 所有记录日期均大于输入日期,无符合条件的结果
        return pd.Index([])
    # 取小于输入日期的最大日期对应的索引
    max_prev_date = prev_records['Date'].max()
    return prev_records[prev_records['Date'] == max_prev_date].index

# 测试示例
print(get_target_index('01-03-2018'))  # 返回01-12-2017对应的所有行索引
print(get_target_index('01-09-2018'))  # 返回01-12-2017对应的所有行索引
print(get_target_index('01-12-2018'))  # 返回完全匹配的01-12-2018对应的所有行索引

高性能实现代码(适合大数据量)

如果数据量较大,可以提前对日期列排序后用searchsorted快速定位,避免全表扫描:

# 提前按日期排序并提取排序后的日期序列,仅需执行一次
df_sorted = df.sort_values('Date', ignore_index=False).reset_index(names='original_index')
sorted_date_series = df_sorted['Date']

def get_target_index_fast(input_date_str):
    input_date = pd.to_datetime(input_date_str, dayfirst=True)
    # 二分查找定位位置
    position = sorted_date_series.searchsorted(input_date, side='right') - 1
    if position < 0:
        return pd.Index([])
    target_date = sorted_date_series.iloc[position]
    return df_sorted[df_sorted['Date'] == target_date]['original_index']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 05:33:03