您可以使用join
使用两个具有相同索引的数据框一次性创建一堆列。
首先,使用计算总和groupby
反对axis=1
ndf = df.groupby(df.columns.get_level_values(0), axis=1).sum()
bar baz
A 0.963228 1.910958
B 0.917711 0.729774
C -0.312510 -0.432796
(PS:如果你有两列以上,你可以这样做
df.loc[:, (slice(None), ['one', 'two'])].groupby(df.columns.get_level_values(0), axis=1).sum()
首先只切片“一”和“二”列,然后then groupby
)
然后,使其与您的列索引匹配,即使其成为多索引数据框,就像原始数据框一样
ndf.columns = pd.MultiIndex.from_product([ndf.columns, ['three']])
bar baz
three three
A 0.963228 1.910958
B 0.917711 0.729774
C -0.312510 -0.432796
最后,df.join https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.join.html
finaldf = df.join(ndf).sort_index(axis=1)
如果您真的关心顺序,请使用reindex
finaldf.reindex(['one', 'two', 'three'], axis=1, level=1)
first bar baz
second one two three one two three
A -1.089798 2.053026 0.963228 0.470218 1.440740 1.910958
B 0.488875 0.428836 0.917711 1.413451 -0.683677 0.729774
C -0.243064 -0.069446 -0.312510 -0.911166 0.478370 -0.432796