2016-07-13 105 views
0

特定水平的考虑这两个dataframes:如何将数据帧追加到另一个数据框

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其中df1df1.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

首先我重新分配的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 
相关问题