RollingGroupby 上的 Pandas 聚合方法 [英] Pandas Aggregate Method on RollingGroupby

查看:34
本文介绍了RollingGroupby 上的 Pandas 聚合方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题: .agg 方法是否适用于 RollingGroupby 对象?似乎它应该并且 IPython 自动填充此方法,但我收到一个错误.

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.

文档:我没有看到任何特定于 RollingGroupby 对象的内容.我可能找错了地方,但我查看了 标准移动窗口函数GroupBy

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

样本数据:

# 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

这对我不起作用.

df.groupby(['animal', 'period'])['value'].rolling(2).agg(['count', 'mean'])

简短的例外是:

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

推荐答案

Jeff(Pandas 的主要开发者之一):

Jeff (one of the main Pandas developers) said:

复杂的 .agg 从未在.groupby.rolling,所以这不起作用也就不足为奇了.

sophisticated .agg was never explicitly implemented on .groupby.rolling, so not surprising this doesn't work.

这篇关于RollingGroupby 上的 Pandas 聚合方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆