在熊猫中使用分组,滚动和滚动

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

我正在尝试计算组内的滚动平均值。对于此任务,我希望从上面的行中获得滚动平均值,因此认为最简单的方法是使用shift()然后执行rolling()。问题是shift()将先前组中的数据移位,从而使组2和3中的第一行不正确。 “ ma”列的第4行和第7行应为NaN。如何实现?

import pandas as pd

df = pd.DataFrame(
    {"Group": [1, 2, 3, 1, 2, 3, 1, 2, 3],
     "Value": [2.5, 2.9, 1.6, 9.1, 5.7, 8.2, 4.9, 3.1, 7.5]
     })

df = df.sort_values(['Group'])
df.reset_index(inplace=True)

df['ma'] = df.groupby('Group', as_index=False)['Value'].shift(1).rolling(3, min_periods=1).mean()

print(df)

我明白了:

   index  Group  Value    ma
0      0      1    2.5   NaN
1      3      1    9.1  2.50
2      6      1    4.9  5.80
3      1      2    2.9  5.80
4      4      2    5.7  6.00
5      7      2    3.1  4.30
6      2      3    1.6  4.30
7      5      3    8.2  3.65
8      8      3    7.5  4.90

我尝试了几个类似问题的答案,但似乎无济于事。

python python-3.x pandas pandas-groupby
1个回答
1
投票

如果我正确理解了问题,则可以使用以下步骤通过两个步骤来实现所需的解决方案:

df['sa'] = df.groupby('Group', as_index=False)['Value'].transform(lambda x: x.shift(1))

df['ma'] = df.groupby('Group', as_index=False)['sa'].transform(lambda x: x.rolling(3, min_periods=1).mean())

我得到以下输出,其中“ ma”是所需的列

index   Group   Value   sa  ma
0   0   1   2.5     NaN     NaN
1   3   1   9.1     2.5     2.5
2   6   1   4.9     9.1     5.8
3   1   2   2.9     NaN     NaN
4   4   2   5.7     2.9     2.9
5   7   2   3.1     5.7     4.3
6   2   3   1.6     NaN     NaN
7   5   3   8.2     1.6     1.6
8   8   3   7.5     8.2     4.9

编辑:具有一个分组依据的示例

def shift_ma(x):
    return x.shift(1).rolling(3, min_periods=1).mean()

df['ma'] = df.groupby('Group', as_index=False)['Value'].apply(shift_ma).reset_index(drop=True)
© www.soinside.com 2019 - 2024. All rights reserved.