pandas 中多索引数据框中一列的平均值

average of one column in multi index dataframe in pandas

我有一个与此类似的多索引数据框。

arrays = [np.array(['bar', 'bar', 'bar','baz', 'baz', 'baz', 'foo', 'foo', 'foo']),
      np.array(['one', 'two', 'three', 'one', 'two', 'three','one', 'two','three'])]
s = pd.Series(np.random.randn(9), index=arrays)
df = pd.DataFrame(np.random.randn(9, 2), index=arrays,columns=['C1','C2'])
df

我想在数据框的末尾添加一个新列,该列将按 level=0 ('bar','baz','foo') 分组,并对列中的数字进行平均这些组的 C2。我想在一种情况下(或者在每个级别 = 0 的顶行)位置

试试 transform mean

df.groupby(level=0).transform('mean')
                 C1        C2
bar one    0.473968 -0.454709
    two    0.473968 -0.454709
    three  0.473968 -0.454709
baz one    0.731266 -0.437691
    two    0.731266 -0.437691
    three  0.731266 -0.437691
foo one    0.061087 -0.326533
    two    0.061087 -0.326533
    three  0.061087 -0.326533

更新

df['C3']=df.groupby(level=0).C2.transform('mean')