分组滚动

问题描述 投票:1回答:1

考虑这个简单的例子

df = pd.DataFrame({'date' : [pd.to_datetime('2018-01-01'), 
                             pd.to_datetime('2018-01-01'), 
                             pd.to_datetime('2018-01-01'), 
                             pd.to_datetime('2018-01-01')],
                   'group' : ['a','a','b','b'],
                   'value' : [1,2,3,4],
                   'value_useless' : [2,2,2,2]})

df
Out[78]: 
        date group  value  value_useless
0 2018-01-01     a      1              2
1 2018-01-01     a      2              2
2 2018-01-01     b      3              2
3 2018-01-01     b      4              2

在这里,我想按组计算value的滚动总和。我试着这么简单

df['rolling_sum'] = df.groupby('group').value.rolling(2).sum()
TypeError: incompatible index of inserted column with frame index

使用apply的变体似乎也不起作用

df['rolling_sum'] = df.groupby('group').apply(lambda x: x.value.rolling(2).sum())
TypeError: incompatible index of inserted column with frame index

我在这里错过了什么?谢谢!

python pandas
1个回答
2
投票

groupby正在添加一个阻碍你的方式的索引级别。

rs = df.groupby('group').value.rolling(2).sum()
df.assign(rolling_sum=rs.reset_index(level=0, drop=True))

        date group  value  value_useless  rolling_sum
0 2018-01-01     a      1              2          NaN
1 2018-01-01     a      2              2          3.0
2 2018-01-01     b      3              2          NaN
3 2018-01-01     b      4              2          7.0

details

rs

# Annoying Index Level
# |
# v
# group   
# a      0    NaN
#        1    3.0
# b      2    NaN
#        3    7.0
# Name: value, dtype: float64

或者,您可以使用pd.concat绕过添加的索引

df.assign(rolling_sum=pd.concat(s.rolling(2).sum() for _, s in df.groupby('group').value))

        date group  value  value_useless  rolling_sum
0 2018-01-01     a      1              2          NaN
1 2018-01-01     a      2              2          3.0
2 2018-01-01     b      3              2          NaN
3 2018-01-01     b      4              2          7.0
© www.soinside.com 2019 - 2024. All rights reserved.