2017-01-23 115 views
1

不同列的备用元素我有2分dataframes列如下:使用熊猫

df1 = pd.DataFrame({'A':['CINO','KONO','ROLO','MANE','TUTU']}) 
df2 = pd.DataFrame({'B':['NION','PONO','RZCO','MPPE','TQAS']}) 

我的想法是把dataframes以这样的方式相结合,输出看起来像这样:

 C 
CC1 CINO <---- belongs to A 
CC1 NION <---- belongs to B 
CC2 KONO <---- belongs to A  
CC2 PONO <---- belongs to B 
CC3 ROLO <---- belongs to A 
CC3 RZCO <---- belongs to B 
CC4 MANE <---- belongs to A 
CC4 MPPE <---- belongs to B 
CC5 TUTU <---- belongs to A 
CC5 TQAS <---- belongs to B 

如您所见,列B的项目位于列A的行之间。 请注意,行的命名方式是每对行具有相同的名称。

你可以建议我一个聪明的方法来实现这个目标使用一些内置的熊猫功能?

回答

4
pd.concat(
    [df1, df2], axis=1 
).stack().reset_index(1, drop=True).to_frame('C').rename(index='CC{}'.format) 

     C 
CC0 CINO 
CC0 NION 
CC1 KONO 
CC1 PONO 
CC2 ROLO 
CC2 RZCO 
CC3 MANE 
CC3 MPPE 
CC4 TUTU 
CC4 TQAS 
2

您可以使用:

df = pd.concat([df1.rename(columns={'A':'C'}), 
       df2.rename(columns={'B':'C'})], keys=[1,2]) 
     .sort_index(level=[1,0]) 
     .reset_index(level=0, drop=True) 
df.index = 'CC' + df.index.astype(str) 
print (df) 
     C 
CC0 CINO 
CC0 NION 
CC1 KONO 
CC1 PONO 
CC2 ROLO 
CC2 RZCO 
CC3 MANE 
CC3 MPPE 
CC4 TUTU 
CC4 TQAS