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

如何让Pandas resample的last方法保留区间末位空值NaN?

时间序列重采样后填充最近值(含NaN)的需求

原始时间序列

ts
Out[20]: 
time
2023-08-01 10:31:40.110    6.22
2023-08-01 10:31:43.110    6.23
2023-08-01 10:31:46.111    6.23
2023-08-01 10:31:49.111    6.24
2023-08-01 10:31:52.111    6.24
2023-08-01 10:31:55.117    6.25
2023-08-01 10:31:58.112     NaN
2023-08-01 10:32:01.112     NaN
2023-08-01 10:32:04.117     NaN
2023-08-01 10:32:07.095     NaN

当前重采样代码及结果

执行代码:

ts.resample('6S', closed='left', label='right').last()

得到结果:

Out[21]: 
time
2023-08-01 10:31:42    6.22
2023-08-01 10:31:48    6.23
2023-08-01 10:31:54    6.24
2023-08-01 10:32:00    6.25
2023-08-01 10:32:06     NaN
2023-08-01 10:32:12     NaN

需求说明

希望2023-08-01 10:32:00这个位置填充为该时间点之前的最后一个实际值(包含NaN),当前场景下该位置应显示为NaN。

生成原始序列的代码

import pandas as pd
import numpy as np

ts = pd.Series(
    [6.22, 6.23, 6.23, 6.24, 6.24, 6.25, np.nan, np.nan, np.nan, np.nan],
    index=pd.DatetimeIndex(
        ['2023-08-01 10:31:40.110000', '2023-08-01 10:31:43.110000',
         '2023-08-01 10:31:46.111000', '2023-08-01 10:31:49.111000',
         '2023-08-01 10:31:52.111000', '2023-08-01 10:31:55.117000',
         '2023-08-01 10:31:58.112000', '2023-08-01 10:32:01.112000',
         '2023-08-01 10:32:04.117000', '2023-08-01 10:32:07.095000'],
        dtype='datetime64[ns]', name='exchange_time', freq=None
    )
)

解决方案

实现代码

# 先生成重采样后的目标索引
resampled_idx = ts.resample('6S', closed='left', label='right').last().index

# 遍历每个索引,取该时间点之前的最后一个原始值(含NaN)
result = pd.Series(
    [ts.loc[:idx].iloc[-1] if not ts.loc[:idx].empty else np.nan for idx in resampled_idx],
    index=resampled_idx,
    name=ts.name
)

执行结果

exchange_time
2023-08-01 10:31:42    6.22
2023-08-01 10:31:48    6.23
2023-08-01 10:31:54    6.24
2023-08-01 10:32:00     NaN
2023-08-01 10:32:06     NaN
2023-08-01 10:32:12     NaN

原理说明

  • ts.loc[:idx]筛选出所有时间小于等于当前重采样标签的原始数据点
  • .iloc[-1]直接取该子集的最后一个值,无论它是数值还是NaN,完全保留原始序列的最后记录状态
  • 这种方式避开了resample().last()自动忽略区间内NaN的逻辑,精准匹配需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 17:45:58