使用 pandas' groupby 进行移位

Using pandas' groupby with shifting

我希望在 groupby 操作中使用 pd.rolling_mean。我想在每个组中对同一组中的 previous elemnet 进行滚动平均。这是一个例子:

id    val
0     1
0     2
0     3
1     4
1     5
2     6

id分组,这应该转化为:

id    val
0     nan
0     1
0     1.5
1     nan
1     4
2     nan

我认为你需要 groupbyshiftrolling,window 大小可以设置为标量:

df['val']=df.groupby('id')['val'].apply(lambda x: x.shift().rolling(2, min_periods=1).mean())
print (df)
   id  val
0   0  NaN
1   0  1.0
2   0  1.5
3   1  NaN
4   1  4.0
5   2  NaN

感谢 的评论 - 您可以根据组的最大长度设置 window 大小:

f = lambda x: x.shift().rolling(df['id'].value_counts().iloc[0], min_periods=1).mean()
df['val'] = df.groupby('id')['val'].apply(f)
print (df)
   id  val
0   0  NaN
1   0  1.0
2   0  1.5
3   1  NaN
4   1  4.0
5   2  NaN

我相信你想要pd.Series.expanding

df.groupby('id').val.apply(lambda x: x.expanding().mean().shift())

0    NaN
1    1.0
2    1.5
3    NaN
4    4.0
5    NaN
Name: val, dtype: float64