熊猫在 groupby 上的滚动平均值

时间:2021-03-05 12:13:50

标签: python pandas pandas-groupby

我想知道在带有 rollinggroupby 对象上应用 MuliIndex 的行为是否符合预期。问题是直接在 rolling 上使用 groupby 不会保留 MultiIndex。但是,在 apply 上使用 groupby 会保留索引。

df = pd.DataFrame([1, 2, 3, 4], index=pd.MultiIndex.from_arrays([[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']], names=['number', 'color']))

我想计算 level='number' 中每组的滚动平均值。直接在 rolling 上应用 groupby,结果由单个 level='number' 索引,删除 level='color'

df.groupby(level='number').rolling(window=2).mean()


          0
number     
1       NaN
1       1.5
2       NaN
2       3.5

我可以在 apply 上使用 groupby 获得想要的结果

df.groupby(level='number').apply(lambda x: x.rolling(2).mean())

                0
number color     
1      red    NaN
       blue   1.5
2      red    NaN
       blue   3.5

groupby().rolling()MultiIndex 上的行为是错误吗?

1 个答案:

答案 0 :(得分:0)

此行为是一个错误,将在 pandas 1.2.3 版中修复,请参阅 GitHub 上的 pandas 存储库中报告的 this issue