python - Pandas .resample() 或 .asfreq() 向前填充时间

标签 python pandas time-series resampling

我正在尝试使用从 1 小时增量到 15 分钟的时间序列对数据帧进行重新采样。 .resample().asfreq() 几乎完全符合我的要求,但我很难填补最后三个间隔。

我可以在最后增加一个小时,重新采样,然后删除最后一个小时,但这感觉很糟糕。

当前代码:

df = pd.DataFrame({'date':pd.date_range('2018-01-01 00:00', '2018-01-01 01:00', freq = '1H'), 'num':5})
df = df.set_index('date').asfreq('15T', method = 'ffill', how = 'end').reset_index()

当前输出:

                 date  num
0 2018-01-01 00:00:00    5
1 2018-01-01 00:15:00    5
2 2018-01-01 00:30:00    5
3 2018-01-01 00:45:00    5
4 2018-01-01 01:00:00    5

期望的输出:

                 date  num
0 2018-01-01 00:00:00    5
1 2018-01-01 00:15:00    5
2 2018-01-01 00:30:00    5
3 2018-01-01 00:45:00    5
4 2018-01-01 01:00:00    5
5 2018-01-01 01:15:00    5
6 2018-01-01 01:30:00    5
7 2018-01-01 01:45:00    5

想法?

最佳答案

不确定 asfreqreindex 工作得很好:

df.set_index('date').reindex(
      pd.date_range(
          df.date.min(), 
          df.date.max() + pd.Timedelta('1H'), freq='15T', closed='left'
      ), 
      method='ffill'
)

                     num
2018-01-01 00:00:00    5
2018-01-01 00:15:00    5
2018-01-01 00:30:00    5
2018-01-01 00:45:00    5
2018-01-01 01:00:00    5
2018-01-01 01:15:00    5
2018-01-01 01:30:00    5
2018-01-01 01:45:00    5

关于python - Pandas .resample() 或 .asfreq() 向前填充时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49387205/

相关文章:

python - 从一个 Pandas 数据框中减去另一列

r - 在 Forecast() 和 ar() 中传递参数时 R 中的预测错误

python - Python 中的响应面建模和优化 : Analogous to rsm in R?

python - 使用 Centos 7 和 Python 3.4 的 PIL

python - 无法使用 python 在 azure 函数中使用 pandas 读取 csv

python - 带返回值的 DataFrame 就地修改

r - 不规则数据的时间序列建模

python - 在 Pandas 中按整数天计算滚动平均值

python - 使用 Python 参数替换将记录插入到 Sqlite 中,其中某些字段为空白

python - 获取 numpy 数组的所有子序列