首页 > 解决方案 > 将年度时间序列转换为月度

问题描述

如果我的 df 索引有 '01-01-2000'、'01-01-2001'、'01-01-2002' 等,我如何将年度时间序列转换为月度。带有“M”的重采样方法有效,但每月系列停止在去年的“01-01”,但我希望去年的“12-01”在该范围内。感谢任何帮助。

标签: python-3.xpandastime-series

解决方案


您可以尝试添加最后一个假观察(正如 Quang Hoang 建议的那样):

import pandas as pd
import numpy as np

df = pd.DataFrame({'date': pd.date_range('2001-01-01', periods = 5, freq = 'AS'), 'Value_1': np.random.randint(0, 100, 4).tolist() + [np.NaN]})
df = df.set_index('date')
print(df)

原始系列于 2004-01-01 结束。

df_out = df.resample('MS').ffill()
print(df_out)

新系列于 2004-12-01 结束。


推荐阅读