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

56 multi-index pandas

我想在multiindex列数据帧的第二级添加一列.

In [151]: df
Out[151]: 
first        bar                 baz           
second       one       two       one       two 
A       0.487880 -0.487661 -1.030176  0.100813 
B       0.267913  1.918923  0.132791  0.178503
C       1.550526 -0.312235 -1.177689 -0.081596 
Run Code Online (Sandbox Code Playgroud)

通常的直接分配技巧不起作用:

In [152]: df['bar']['three'] = [0, 1, 2]

In [153]: df
Out[153]: 
first        bar                 baz           
second       one       two       one       two 
A       0.487880 -0.487661 -1.030176  0.100813
B       0.267913  1.918923  0.132791  0.178503
C       1.550526 -0.312235 -1.177689 -0.081596
Run Code Online (Sandbox Code Playgroud)

如何将第三行添加到"bar"下?

spe*_*on2 64

它实际上非常简单(FWIW,我原本以为你的方式):

df['bar', 'three'] = [0, 1, 2]
df = df.sort_index(axis=1)
print(df)

        bar                        baz          
        one       two  three       one       two
A -0.212901  0.503615      0 -1.660945  0.446778
B -0.803926 -0.417570      1 -0.336827  0.989343
C  3.400885 -0.214245      2  0.895745  1.011671
Run Code Online (Sandbox Code Playgroud)

  • 对不起,这不是答案的一部分,只是我挑剔.一旦你调用`df ['bar','three'] = [0,1,2]`它就会显示出来.默认情况下,pandas会将它放在DataFrame的末尾(在[baz,two]之后).我只想和另一个酒吧一起看. (3认同)
  • 这会将新列“三”附加到子表“栏”。但是,如果您想在子表“bar”中插入(而不是附加)这个新列,例如在“一”和“二”之间插入“三”,该怎么办? (2认同)
  • 是否可以将其概括为向每个子索引添加第三列?(即在本例中为“bar”和“baz”添加“三”列? (2认同)

Max*_*axU 8

如果我们要添加多级列:

来源DF:

In [221]: df
Out[221]:
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
Run Code Online (Sandbox Code Playgroud)

选项1:添加除法结果:bar / baz作为新foo

In [222]: df = df.join(df[['bar']].div(df['baz']).rename(columns={'bar':'foo'}))

In [223]: df
Out[223]:
first        bar                 baz                 foo
second       one       two       one       two       one       two
A      -1.089798  2.053026  0.470218  1.440740 -2.317647  1.424980
B       0.488875  0.428836  1.413451 -0.683677  0.345873 -0.627250
C      -0.243064 -0.069446 -0.911166  0.478370  0.266761 -0.145172
Run Code Online (Sandbox Code Playgroud)

选项2:添加具有三个"子列"的多级列:

In [235]: df = df.join(pd.DataFrame(np.random.rand(3,3),
     ...:                           columns=pd.MultiIndex.from_product([['new'], ['one','two','three']]),
     ...:                             index=df.index))

In [236]: df
Out[236]:
first        bar                 baz                 new
second       one       two       one       two       one       two     three
A      -1.089798  2.053026  0.470218  1.440740  0.274291  0.636257  0.091048
B       0.488875  0.428836  1.413451 -0.683677  0.668157  0.456931  0.227568
C      -0.243064 -0.069446 -0.911166  0.478370  0.333824  0.363060  0.949672
Run Code Online (Sandbox Code Playgroud)