我有一個類似于此的多索引數據幀。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我想在數據幀的末尾添加一個新列,該列將按級別=0(“bar”,“baz”,“foo”)分組,并對這些組的C2列中的數字進行平均。我想在一個場景中(或者在每個級別= 0的頂行)位置顯示3個單獨行中每個行的相同平均數
1 回答

侃侃爾雅
TA貢獻1801條經驗 獲得超16個贊
嘗試使用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')
添加回答
舉報
0/150
提交
取消