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

如何为DataFrame每行匹配提前至少20秒的最近前置行?

问题

针对DataFrame的每一行,需要找到最近的前置行,要求该行的'Datetime'值比当前行的'Datetime'值至少早20秒。具体规则:

  • 优先检查前一行(索引i-1),若时间差≥20秒则选中该行;
  • 若不满足则继续查找索引i-2的行,直到找到符合条件的行或确认无匹配;
  • 最终结果需将原DataFrame与匹配行拼接,未找到匹配时新增列用NaT(日期类型)或NaN(数值类型)填充。

示例数据

import pandas as pd

df = pd.DataFrame({
    'Datetime': pd.to_datetime([
        f'2016-05-15 08:{M_S}+06:00'
        for M_S in ['36:21', '36:41', '36:50', '37:10', '37:19', '37:39']]),
    'A': [21, 43, 54, 2, 54, 67],
    'B': [3, 3, 45, 23, 8, 6],
})

预期结果

>>> res
                  Datetime   A   B              Datetime_nearest  A_nearest  B_nearest
0 2016-05-15 08:36:21+06:00  21   3                           NaT        NaN        NaN
1 2016-05-15 08:36:41+06:00  43   3 2016-05-15 08:36:21+06:00       21.0        3.0
2 2016-05-15 08:36:50+06:00  54  45 2016-05-15 08:36:21+06:00       21.0        3.0
3 2016-05-15 08:37:10+06:00   2  23 2016-05-15 08:36:50+06:00       54.0       45.0
4 2016-05-15 08:37:19+06:00  54   8 2016-05-15 08:36:50+06:00       54.0       45.0
5 2016-05-15 08:37:39+06:00  67   6 2016-05-15 08:37:19+06:00       54.0        8.0
解决方案

方法1:merge_asof高效匹配(推荐大数据集)

pandas.merge_asof专门用于按时间序列匹配最近的前置/后置行,我们通过给当前时间减去20秒,将匹配条件转化为"找时间≤当前时间-20秒的最近行",实现高效批量匹配。

代码实现:

import pandas as pd

# 计算当前时间减20秒,作为匹配的时间上限
df['Datetime_threshold'] = df['Datetime'] - pd.Timedelta(seconds=20)

# 执行时间匹配,找最近的符合条件的前置行
result = pd.merge_asof(
    df,
    # 重命名原表列,避免合并后列名冲突
    df.rename(columns={
        'Datetime': 'Datetime_nearest',
        'A': 'A_nearest',
        'B': 'B_nearest'
    }),
    left_on='Datetime_threshold',
    right_on='Datetime_nearest',
    direction='backward'  # 匹配小于等于left_on值的最近行
)

# 移除临时辅助列
result.drop('Datetime_threshold', axis=1, inplace=True)

print(result)

方法2:循环遍历(适合小数据集)

如果数据集规模较小,直接循环每行向前查找第一个满足时间差要求的行即可,逻辑直观易懂。

代码实现:

import pandas as pd

# 初始化新增列
df['Datetime_nearest'] = pd.NaT
df['A_nearest'] = pd.NA
df['B_nearest'] = pd.NA

# 从第二行开始遍历
for i in range(1, len(df)):
    current_dt = df.loc[i, 'Datetime']
    # 从当前行的前一行开始向前查找
    for j in range(i-1, -1, -1):
        time_diff = current_dt - df.loc[j, 'Datetime']
        if time_diff >= pd.Timedelta(seconds=20):
            # 找到匹配行,填充对应列
            df.loc[i, ['Datetime_nearest', 'A_nearest', 'B_nearest']] = df.loc[j, ['Datetime', 'A', 'B']]
            break  # 找到最近的就停止查找

print(df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:36:17