Python-GroupBy对象的滚动功能 [英] Python - rolling functions for GroupBy object
本文介绍了Python-GroupBy对象的滚动功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类型为<pandas.core.groupby.SeriesGroupBy object at 0x03F1A9F0>
的时间序列对象grouped
. grouped.sum()
给出了所需的结果,但是我无法获得rolling_sum与groupby
对象一起使用.有什么方法可以将滚动功能应用于groupby
对象?例如:
I have a time series object grouped
of the type <pandas.core.groupby.SeriesGroupBy object at 0x03F1A9F0>
. grouped.sum()
gives the desired result but I cannot get rolling_sum to work with the groupby
object. Is there any way to apply rolling functions to groupby
objects? For example:
x = range(0, 6)
id = ['a', 'a', 'a', 'b', 'b', 'b']
df = DataFrame(zip(id, x), columns = ['id', 'x'])
df.groupby('id').sum()
id x
a 3
b 12
但是,我想要这样的东西:
However, I would like to have something like:
id x
0 a 0
1 a 1
2 a 3
3 b 3
4 b 7
5 b 12
推荐答案
注意:由@kekert标识,以下熊猫模式已被弃用.请在下面的答案中查看当前的解决方案.
Note: as identified by @kekert, the following pandas pattern has been deprecated. See current solutions in the answers below.
In [16]: df.groupby('id')['x'].apply(pd.rolling_mean, 2, min_periods=1)
Out[16]:
0 0.0
1 0.5
2 1.5
3 3.0
4 3.5
5 4.5
In [17]: df.groupby('id')['x'].cumsum()
Out[17]:
0 0
1 1
2 3
3 3
4 7
5 12
这篇关于Python-GroupBy对象的滚动功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文