分层操作Pandas

Hierarchical Operation Pandas

显然我遗漏了一些简单的东西,但我不知道是什么。我想按组传播操作。让我们说一些简单的事情,我有一个简单的多索引系列(假设 2 个级别),我想取平均值并将该平均值减去正确的索引级别。

极简示例代码:

a = pd.Series({(2,1): 3., (1,2):4.,(2,3):4.})
b = a.groupby(level=0).mean()
r = a-b # this is the wrong line, b doesn't propagate to the multiindex of a

我期望的结果:

2  1    -0.5
1  2    0
2  3    .5
dtype: float64

使用 Series.sub 和可能定义的对齐级别:

r = a.sub(b, level=0)
print (r)
2  1   -0.5
1  2    0.0
2  3    0.5
dtype: float64

或对 Series 使用 GroupBy.transform 与原始索引相同 a Series:

b = a.groupby(level=0).transform('mean')
r = a-b
print (r)
2  1   -0.5
1  2    0.0
2  3    0.5
dtype: float64