Reputation: 736
Question: Does the .agg method work on a RollingGroupby object? It seems like it should and IPython auto populates for this method, but I'm getting an error.
Documentation: I did not see anything specific to RollingGroupby
objects. I am probably looking in the wrong place, but i looked at Standard moving window functions and GroupBy
Sample Data:
# test data
df = pd.DataFrame({
'animal':np.random.choice( ['panda','python','shark'], 12),
'period':np.repeat(range(3), 4 ),
'value':np.tile(range(2), 6 ),
})
# this works as expected
df.groupby(['animal', 'period'])['value'].rolling(2).count()
animal period
panda 0 2 1.0
2 8 1.0
10 2.0
python 0 0 1.0
1 2.0
1 6 1.0
2 11 1.0
shark 0 3 1.0
1 4 1.0
5 2.0
7 2.0
2 9 1.0
Name: value, dtype: float64
# this works as expected
df.groupby(['animal', 'period'])['value'].rolling(2).mean()
animal period
panda 0 2 NaN
2 8 NaN
10 0.0
python 0 0 NaN
1 0.5
1 6 NaN
2 11 NaN
shark 0 3 NaN
1 4 NaN
5 0.5
7 1.0
2 9 NaN
Name: value, dtype: float64
This does not work for me.
df.groupby(['animal', 'period'])['value'].rolling(2).agg(['count', 'mean'])
The short exception is:
Exception: Column(s) value already selected
The desired DataFrame is below. I got this from merging the two DataFrames that worked above, but this seems cumbersome.
animal period level_2 value_x value_y
0 panda 0 2 1.0 NaN
1 panda 2 8 1.0 NaN
2 panda 2 10 2.0 0.0
3 python 0 0 1.0 NaN
4 python 0 1 2.0 0.5
5 python 1 6 1.0 NaN
6 python 2 11 1.0 NaN
7 shark 0 3 1.0 NaN
8 shark 1 4 1.0 NaN
9 shark 1 5 2.0 0.5
10 shark 1 7 2.0 1.0
11 shark 2 9 1.0 NaN
Upvotes: 2
Views: 1774
Reputation: 210822
Jeff (one of the main Pandas developers) said:
sophisticated
.agg
was never explicitly implemented on.groupby.rolling
, so not surprising this doesn't work.
Upvotes: 2