我有一个这样的系列
index = pd.date_range('2000-01-01 00:00:00', periods=9, freq='T')
index = index.append(pd.date_range('2000-01-01 00:11:00', periods=5, freq='T'))
index = index.append(pd.date_range('2000-01-01 00:17:00', periods=5, freq='T'))
series = pd.Series(range(len(index)), index=index)
如您所见,我故意在时间索引上留下一些漏洞,以便在我重新采样时,采样仓的开始或结束可能不会落在现有的索引值上。 我想要实现的是这样
series.resample(freq).apply(time_weight)
在我的time_weight
函数中,我要加权平均值,以该样本仓开始处的距离除以样本仓宽度(在freq
中为timedelta
)来加权。但是似乎没有办法知道样品仓的开始吗?
答案 0 :(得分:1)
您可以先计算权重:
# create dataframe for easy manipulation
df = pd.DataFrame({'val': series}).reset_index()
# sample frequency
freq = '5T'
# groupby
groups = df.groupby(df['index'].dt.floor(freq ))
# base and weights:
df['base'] = groups['index'].transform(lambda x: x.iloc[0].floor('5T'))
df['weight'] = (df['index'] - df['base']).dt.total_seconds()
# apply:
groups.apply(lambda x: x['val']*x['weight']/x['weight'].sum())
输出:
index
2000-01-01 00:00:00 0 0.000000
1 0.100000
2 0.400000
3 0.900000
4 1.600000
2000-01-01 00:05:00 5 0.000000
6 1.000000
7 2.333333
8 4.000000
2000-01-01 00:10:00 9 0.900000
10 2.000000
11 3.300000
12 4.800000
2000-01-01 00:15:00 13 0.000000
14 3.111111
15 5.000000
16 7.111111
2000-01-01 00:20:00 17 0.000000
18 18.000000
dtype: float64