首页 > 解决方案 > Pandas:将多列添加到多索引列数据框中

问题描述

这个问题试图概括为这个问题提供的解决方案:

Pandas:向多索引列数据框添加一列

我需要为每个列索引生成一列。

spencerlyon2当我们要添加单列时,提供的解决方案有效:

df['bar', 'three'] = [0, 1, 2]

但是,我想为每个第一级列索引概括此操作。

来源 DF:

In [1]: df
Out[2]:
first        bar                 baz
second       one       two       one       two
A      -1.089798  2.053026  0.470218  1.440740
B       0.488875  0.428836  1.413451 -0.683677
C      -0.243064 -0.069446 -0.911166  0.478370

下面的目标 DF,要求该列是其各自索引的和列three的相加。onetwo

In [1]: df
Out[2]:
first        bar                           baz                 
second       one       two     three       one       two      three
A      -1.089798  2.053026  0.963228‬  1.440740 -2.317647  -0.876907‬
B       0.488875  0.428836  0.917711 -0.683677  0.345873  -0.337804‬
C      -0.243064 -0.069446 -0.312510  0.478370  0.266761   0.745131‬

标签: pythonpandas

解决方案


您可以使用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()

先只切片“一”和“二”列,然后再 groupby切片)

然后,使其与您的列索引匹配,即使其成为 MultiIndexed 数据框,就像您的原始数据框一样

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

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

推荐阅读