Akash Warkhade
Akash Warkhade

Reputation: 69

Pandas dataframe vertical merge

I have a query regarding merging two dataframes For example i have 2 dataframes as below :

print(df1)

   Year   Location  
0  2013    america     
1  2008     usa       
2  2011     asia   



print(df2)

   Year Location  
0  2008      usa       
1  2008      usa       
2  2009     asia  

My expected output :

Year   Location  
2013    america     
2008     usa       
2011     asia

Year   Location
2008      usa       
2008      usa       
2009     asia

Output i am getting right now :

Year   Location    Year   Location
2013   america    2008    usa
2008    usa       2008    usa
2011    asia      2009    asia

I have tried using pd.concat and pd.merge with no luck

Please help me with above

Upvotes: 3

Views: 12425

Answers (4)

Nick Leliukh
Nick Leliukh

Reputation: 1

output_df = pd.concat([df1, df2], ignore_index=False)

if you'd set ignore_index = True, you lost your original indexes and get 0..n-1 instead

It works for MultiIndex too

Upvotes: 0

Ben G
Ben G

Reputation: 4338

pd.concat([df1, df2]) should work. If all the column headings are the same, it will bind the second dataframe's rows below the first. This graphic from a pandas cheat sheet (https://pandas.pydata.org/Pandas_Cheat_Sheet.pdf) explains it pretty well: enter image description here

Upvotes: 2

Sheldon
Sheldon

Reputation: 4633

Simply specify the axis along which to concatenate (axis=1) in pd.concat:

df_merged=pd.concat([df1,df2],axis=1)

Upvotes: 3

F Blanchet
F Blanchet

Reputation: 1510

It's the same columns and same order, so that you can use: df1.append(df2)

Upvotes: 1

Related Questions