2016-01-06 33 views
0

比方說,我有3個數據幀,每個數據幀都有一個列。在每個df中,行數比前一個稍多。例如對於: ,我想正是這一點:與大熊貓合併,同時保持NaN在底部

df1 =  col1 
     1 a 
     2 b 
     3 c 

df2 =  col2 
     1 x 
     2 y 
     3 z 
     4 w 
     5 q 

df3 =  col3 
     1 A 
     2 B 
     3 C 
     4 D 
     5 E 
     6 F 
     7 G 

,我想正是這一點:

res =  col1 col2 col3 
     1 a  x  A 
     2 b  y  B 
     3 c  z  C 
     4 -  w  D 
     5 -  q  E 
     6 -  -  F 
     7 -  -  G 

也就是說,我要對行留在它們的順序因此NaNs( - )保持在底部。 我嘗試這樣做:

import pandas as pd 
total = pd.DataFrame() 

total = pd.merge(total,df1,how='outer',left_index=True,right_index=True) 
total = pd.merge(total,df2,how='outer',left_index=True,right_index=True) 
total = pd.merge(total,df3,how='outer',left_index=True,right_index=True) 

,但我不斷收到表中一個看似隨機的順序。東西像:

res =  col1 col2 col3 
     1 a  x  A 
     4 -  w  D 
     3 c  z  C 
     5 -  q  E 
     2 b  y  B 
     7 -  -  G 
     6 -  -  F 

我該如何強制最終df採取所需的形式? 謝謝!

回答

1

concat並通過axis=1這樣做逐列:

In [203]: 
pd.concat([df1,df2,df3], axis=1) 

Out[203]: 
    col1 col2 col3 
1 a x A 
2 b y B 
3 c z C 
4 NaN w D 
5 NaN q E 
6 NaN NaN F 
7 NaN NaN G