如何将数据框附加到另一个数据框的特定级别

How do I append a dataframe to a specific level of another dataframe

考虑这两个数据框:

df1 = pd.DataFrame(np.arange(16).reshape(4, 4),
                   pd.MultiIndex.from_product([['a', 'b'], ['A', 'B']]),
                   ['One', 'Two', 'Three', 'Four'])

df2 = pd.DataFrame(np.arange(8).reshape(2, 4),
                   ['C', 'D'],
                   ['One', 'Two', 'Three', 'Four'])

print df1

     One  Two  Three  Four
a A    0    1      2     3
  B    4    5      6     7
b A    8    9     10    11
  B   12   13     14    15

print df2

   One  Two  Three  Four
C    0    1      2     3
D    4    5      6     7

我想将 df2 附加到 df1,其中 df1.index 的第一级是 'a'

     One  Two  Three  Four
a A    0    1      2     3
  B    4    5      6     7
  C    0    1      2     3
  D    4    5      6     7
b A    8    9     10    11
  B   12   13     14    15

首先,我将 df2 的索引重新分配给 pd.MultiIndex,并在新索引中包含索引的第一级中的所需位置。

df2.index = pd.MultiIndex.from_product([['a'], df2.index])

然后 concat

pd.concat([df1, df2]).sort_index()

     One  Two  Three  Four
a A    0    1      2     3
  B    4    5      6     7
  C    0    1      2     3
  D    4    5      6     7
b A    8    9     10    11
  B   12   13     14    15