首页 > 解决方案 > Pandas 上采样不包括一年中最后一天的 23 小时

问题描述

我有一个带有日期|天气信息的时间序列数据框,如下所示:

在此处输入图像描述

2017-01-01 5
2017-01-02 10
.
.
2017-12-31 6

我正在尝试使用以下方法将其上采样为每小时数据: weather.resample('H').pad()

我预计会在 24 个间隔 * 365 天内看到 8760 个条目。但是,它仅返回 8737,而 12 月 31 日的最后 23 个间隔缺失。我需要做一些特别的事情来获得最后一天的 24 个间隔吗?

提前致谢。

标签: pythonpandasgoogle-colaboratorypandas-resample

解决方案


Pandas 标准化2017-12-312017-12-31 00:00然后创建一个以最后一个日期时间结束的范围......我将在重新采样之前包含最后一行

df.loc['2018-01-01'] = 0

编辑:你可以得到你想要的结果numpy.repeat

拿这个 df

np.random.seed(1)
weather = pd.DataFrame(index=pd.date_range('2017-01-01', '2017-12-31'),
    data={'WEATHER_MAX': np.random.random(365)*15})

            WEATHER_MAX
2017-01-01     6.255330
2017-01-02    10.804867
2017-01-03     0.001716
2017-01-04     4.534989
2017-01-05     2.201338
...                 ...
2017-12-27     4.503725
2017-12-28     2.145087
2017-12-29    13.519627
2017-12-30     8.123391
2017-12-31    14.621106

[365 rows x 1 columns]

通过重复,axis=1您可以将默认range(24)列名转换为每小时时间差异

# repeat, then stack
hourly = pd.DataFrame(np.repeat(weather.values, 24, axis=1),
    index=weather.index).stack()

# combine date and hour
hourly.index = (
    hourly.index.get_level_values(0) +
    pd.to_timedelta(hourly.index.get_level_values(1), unit='h')
)
hourly = hourly.rename('WEATHER_MAX').to_frame()

输出

                     WEATHER_MAX
2017-01-01 00:00:00     6.255330
2017-01-01 01:00:00     6.255330
2017-01-01 02:00:00     6.255330
2017-01-01 03:00:00     6.255330
2017-01-01 04:00:00     6.255330
...                          ...
2017-12-31 19:00:00    14.621106
2017-12-31 20:00:00    14.621106
2017-12-31 21:00:00    14.621106
2017-12-31 22:00:00    14.621106
2017-12-31 23:00:00    14.621106

[8760 rows x 1 columns]

推荐阅读