Pandas: 将季度数据转换为月度数据。

3

我有一些季度数据,需要将其转换为月度数据以便与另一个数据集配合使用。数据如下:

Date Value
1/1/2010 100
4/1/2010 130
7/1/2010 160

我需要做的是为缺失的月份填充数值,使其看起来像这样:
Date Value
1/1/2010 100
2/1/2010 110
3/1/2010 120
4/1/2010 130
5/1/2010 140
6/1/2010 150
7/1/2010 160

之前没有太多关于如何做到这一点的问题。只有相反的情况(从月度转换为季度)。我尝试了其中一种逆向方法,但它没有起作用:

pd.PeriodIndex(df.Date, freq='M')

什么是在 Pandas 中完成此操作的最简单方法?
1个回答

7
你可以使用 resample
# convert to period
df['Date'] = pd.to_datetime(df['Date']).dt.to_period('M')

# set Date as index and resample
df.set_index('Date').resample('M').interpolate()

输出:

         Value
Date          
2010-01  100.0
2010-02  110.0
2010-03  120.0
2010-04  130.0
2010-05  140.0
2010-06  150.0
2010-07  160.0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接