gpt4 book ai didi

python pandas resample 应用 bin 开始和 bin 宽度

转载 作者:行者123 更新时间:2023-12-01 07:44:30 25 4
gpt4 key购买 nike

我有一个像这样的系列

  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函数,我想通过距样本箱起点的距离除以样本箱宽度来对平均值进行加权,即 freqtimedelta 。但似乎没有办法知道样本箱的开始?

最佳答案

您可以先计算权重:

# 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

关于python pandas resample 应用 bin 开始和 bin 宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56530065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com