我有一个像这样的季度数据的数据框架。
Quarter value
3/31/2014 10500
6/30/2014 10800
9/30/2014 11690
12/31/2014 14200
我想要将季度值转换为月值,以便将3个月的季度值除以3,以此类推。(预期的输出)
Month value
1/31/2014 3500
2/28/2014 3500
3/31/2014 3500
4/30/2014 3600
5/31/2014 3600
6/30/2014 3600
7/31/2014 3896.66
8/31/2014 3896.66
9/30/2014 3896.66
10/31/2014 4733.33
11/30/2014 4733.33
12/31/2014 4733.33
我如何将一个四分之一的值平均分配给3个月?d .resample('M').interpolate()不起作用
将日期时间转换为月周期,然后通过3
重复每一行并用GroupBy.cumcount
减去计数器,最后通过DataFrame.to_timestamp
将周期转换为日期时间并通过Series.dt.normalize
删除时间:
df['Quarter'] = pd.to_datetime(df['Quarter']).dt.to_period('m')
df['value'] /= 3
df = df.iloc[df.index.repeat(3)]
df['Quarter'] = (df['Quarter'].sub(df.groupby(level=0)
.cumcount(ascending=False))
.dt.to_timestamp(how='e').dt.normalize())
df = df.reset_index(drop=True)
print (df)
Quarter value
0 2014-01-31 3500.000000
1 2014-02-28 3500.000000
2 2014-03-31 3500.000000
3 2014-04-30 3600.000000
4 2014-05-31 3600.000000
5 2014-06-30 3600.000000
6 2014-07-31 3896.666667
7 2014-08-31 3896.666667
8 2014-09-30 3896.666667
9 2014-10-31 4733.333333
10 2014-11-30 4733.333333
11 2014-12-31 4733.333333