显然,我遗漏了一些简单的东西,但我不知道是什么。我想按组传播操作。让我们说一些简单的事情,我有一个简单的多指数序列(假设有两个水平),我想取平均值并减去平均值到正确的指数水平。
极简主义示例代码:
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发布于 2021-09-02 07:47:08
使用具有可能定义的级别的Series.sub进行对齐:
r = a.sub(b, level=0)
print (r)
2 1 -0.5
1 2 0.0
2 3 0.5
dtype: float64或者将GroupBy.transform用于具有与原始a Series相同的索引的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: float64https://stackoverflow.com/questions/69026124
复制相似问题