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

2024-04-18 15:07:59 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下两个数据帧:

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

Tags: 数据fromdataframenponepdthreefour
1条回答
网友
1楼 · 发布于 2024-04-18 15:07:59

首先,我用一个pd.MultiIndex重新分配df2的索引,该索引在新索引中包含的索引的第一级中具有所需的位置

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

相关问题 更多 >