python - 重采样时每天保留24h `pandas` `Series`(从每天到每小时)

标签 python pandas datetime

我有一个 pandas Series 有一个(tz-localized)DateTimeIndex 每天一个值:

tmpr
Out[38]: 
2018-01-01 00:00:00+01:00    1.810
2018-01-02 00:00:00+01:00    2.405
2018-01-03 00:00:00+01:00    1.495
2018-01-04 00:00:00+01:00    1.600
2018-01-05 00:00:00+01:00    0.545

2020-12-27 00:00:00+01:00    2.655
2020-12-28 00:00:00+01:00    1.705
2020-12-29 00:00:00+01:00    1.255
2020-12-30 00:00:00+01:00    1.405
2020-12-31 00:00:00+01:00    3.000
Freq: D, Name: tmpr, Length: 1096, dtype: float64

我想将其上采样到每小时的值,以便每个值重复 24 次(或 23 或 25 次,具体取决于夏季/冬季的转换,但这完全是另一回事)。这是我尝试过的:

tmpr.resample('h').ffill()
Out[39]: 
2018-01-01 00:00:00+01:00    1.810
2018-01-01 01:00:00+01:00    1.810
2018-01-01 02:00:00+01:00    1.810
2018-01-01 03:00:00+01:00    1.810
2018-01-01 04:00:00+01:00    1.810

2020-12-30 20:00:00+01:00    1.405
2020-12-30 21:00:00+01:00    1.405
2020-12-30 22:00:00+01:00    1.405
2020-12-30 23:00:00+01:00    1.405
2020-12-31 00:00:00+01:00    3.000
Freq: H, Name: tmpr, Length: 26281, dtype: float64

问题是最后一天:我无法让 resample 包含 0:00 之后的 23 小时。

添加 closed 参数没有任何区别,无论是在重新采样时还是在创建原始时间序列时。

(我尝试用左闭或右闭索引创建原始的 Series:pd.date_range(start=pd.Timestamp(2018, 1, 1), end =pd.Timestamp(2021, 1, 1), freq='D', closed='left')...end=pd.Timestamp(2020, 12, 31),但结果系列看起来是一样的。)

我总是可以在附加日 (2021-01-01) 后附加一个虚拟值,然后在最后将其删除,但这太老套了。

关于如何按预期方式执行此操作的任何想法?

PS - 在以前的项目中,使用 PeriodIndex 而不是 DateTimeIndex,我没有遇到任何问题。但是,我不能在这里使用它,因为它们不支持我确实需要的时区功能。

最佳答案

由于您的数据是每日的,因此您只需创建新的时间戳和reindex:

new_timestamps = pd.date_range(tmpr.index[0], 
                          tmpr.index[-1]+pd.to_timedelta('23H'),
                          freq='H')

tmpr.reindex(new_timestamps).ffill()

输出(样本数据的前半部分):

2018-01-01 00:00:00+01:00    1.810
2018-01-01 01:00:00+01:00    1.810
2018-01-01 02:00:00+01:00    1.810
2018-01-01 03:00:00+01:00    1.810
2018-01-01 04:00:00+01:00    1.810
                             ...  
2018-01-05 19:00:00+01:00    0.545
2018-01-05 20:00:00+01:00    0.545
2018-01-05 21:00:00+01:00    0.545
2018-01-05 22:00:00+01:00    0.545
2018-01-05 23:00:00+01:00    0.545
Freq: H, Name: tmpr, Length: 120, dtype: float64

关于python - 重采样时每天保留24h `pandas` `Series`(从每天到每小时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61761237/

相关文章:

.net - 文化 es-DO 的默认 DateTimeFormat.ShortDatePattern 不正确

C# 对 DateTime 很陌生

python - conda 安装的软件包不适用于 jupyter

python - lightGBM 中的分类特征是如何编码的?

Python re.split() 与 split()

python - 具有日期范围的条形图在绘图中剪切条形图

python - 如何使用 Python 推断给定数据来填充 NaN 值?

python - 读取 pandas 中的所有列作为字符串

python - 模仿排序中的数组交换

javascript - 以这种格式获取当前日期