python - Pandas 上采样不包括一年最后一天的 23 小时

标签 python pandas google-colaboratory pandas-resample

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

2017-01-01 5
2017-01-02 10
.
.
2017-12-31 6
我正在尝试使用以下方法将其上采样为每小时数据:weather.resample('H').pad()我预计在 24 个时间间隔 * 365 天内看到 8760 个条目。但是,它仅返回 8737,其中缺少 12 月 31 日的最后 23 个间隔。我需要做什么特别的事情才能在最后一天获得 24 次间隔?
提前致谢。

最佳答案

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)列名到每小时 timediffs
# 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]

关于python - Pandas 上采样不包括一年最后一天的 23 小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63649213/

相关文章:

python - keras 如何定义 "accuracy"和 "loss"?

python - 如何解析包含不确定数据模式的日志文件?

python - 如何创建新的列名并从其他列的列表中填充行值

python - Pandas 中基于规则的列重命名

python - "Not a valid string."- 尝试将 dict 保存到 Django Rest Framework 中的 TextField 时出错

python - 计算字符串中字符出现的次数

python - 将计算列附加到现有数据框

google-colaboratory - 属性错误 : module 'tensorflow' has no attribute 'gfile'

javascript - 在 Google Colab Notebook 中提供 Iframe : localhost refused to connect

Google Colaboratory 中的 Swift 内核