Python Forum

Full Version: How to join two dataframe
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have below two dataframes, and want to join.

import pandas as pd
import numpy as np

[python]df=pd.DataFrame({'c1':[1,2,3],'c2':[1,2,4],'c3':[2,6,7]})
df1=df.loc[[0],['c1','c2']]
df2=df.loc[[1],['c3']]
result3 = pd.concat([df1, df2], ignore_index=True)
[/python]
I am getting the below result:


    c1   c2    c3
0  1.0   1.0   NaN
1  NaN   NaN   6.0


But I desired is:
   c1    c2    c3
   1.0   1.0   6.0
Probably, what you are looking for is an inner-join operation:

df2=df.loc[[1],['c3']].reset_index().drop('index', axis=1)
df1=df.loc[[0],['c1','c2']].reset_index().drop('index', axis=1)
result3 = pd.concat([df1, df2], join='inner', axis=1)
result3
Output:
c1 c2 c3 0 1 1 6
Note, you can do the same more easily,e.g.
df2=df.loc[[1],['c3']].reset_index()
df1=df.loc[[0],['c1','c2']].reset_index()
result3 = df1.copy()
result3['c3'] = df2.c3.values