考虑这两个数据帧:
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
答案 0 :(得分:0)
首先,我将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