2016-09-29 52 views
3

2数据帧我有2个数据帧列为遵循合并使用类似列

DF

Type  Breed  Common Color Other Color Behaviour 
Golden  Big   Gold   White  Fun  
Corgi  Small   Brown   White  Crazy 
Bulldog Medium   Black   Grey  Strong 

DF2

Type    Breed Behaviour Bark Sound 
Pug    Small  Sleepy   Ak 
German Shepard Big  Cool   Woof 
Puddle   Small  Aggressive  Ek 

我希望通过列TypeBreedBehavior合并2数据帧。

因此,我的愿望输出将是:

Type   Breed  Behavior 
Golden   Big   Fun 
Corgi   Small  Crazy 
Bulldog   Medium  Strong 
Pug    Small  Sleepy 
German Shepard Big   Cool 
Puddle   Small  Aggressive 

回答

4

您需要concat

print (pd.concat([df1[['Type','Breed','Behaviour']], 
        df2[['Type','Breed','Behaviour']]], ignore_index=True)) 

      Type Breed Behaviour 
0   Golden  Big   Fun 
1   Corgi Small  Crazy 
2   Bulldog Medium  Strong 
3    Pug Small  Sleepy 
4 German Shepard  Big  Cool 
5   Puddle Small Aggressive 

更普遍的是使用intersection两个DataFrames列:

cols = df1.columns.intersection(df2.columns) 
print (cols) 
Index(['Type', 'Breed', 'Behaviour'], dtype='object') 

print (pd.concat([df1[cols], df2[cols]], ignore_index=True)) 
      Type Breed Behaviour 
0   Golden  Big   Fun 
1   Corgi Small  Crazy 
2   Bulldog Medium  Strong 
3    Pug Small  Sleepy 
4 German Shepard  Big  Cool 
5   Puddle Small Aggressive 

比较一般如果df1df2没有NaN值使用dropna去除柱与NaN

print (pd.concat([df1 ,df2], ignore_index=True)) 
    Bark Sound Behaviour Breed Common Color Other Color   Type 
0  NaN   Fun  Big   Gold  White   Golden 
1  NaN  Crazy Small  Brown  White   Corgi 
2  NaN  Strong Medium  Black  Grey   Bulldog 
3   Ak  Sleepy Small   NaN   NaN    Pug 
4  Woof  Cool  Big   NaN   NaN German Shepard 
5   Ek Aggressive Small   NaN   NaN   Puddle    


print (pd.concat([df1 ,df2], ignore_index=True).dropna(1)) 
    Behaviour Breed   Type 
0   Fun  Big   Golden 
1  Crazy Small   Corgi 
2  Strong Medium   Bulldog 
3  Sleepy Small    Pug 
4  Cool  Big German Shepard 
5 Aggressive Small   Puddle 
+0

非常感谢你。有用! –

3

使用join删除列不重叠的

df1.T.join(df2.T, lsuffix='_').dropna().T.reset_index(drop=True) 

enter image description here