Search code examples
pythonpandasdataframeconcatenation

Join two data-frames side by side


I have two data frames that I want to join side by side.

They have the same number of rows and I want them next to eachother so I can then total the resulting rows.

So I tried to join using pd.concat

df1 = pd.DataFrame(data.iloc[34:55, 1:19])

df2 = pd.DataFrame(data.iloc[91:112, 1:19])

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

This joins the two data frames one on top of the other and changes 0's to NaN

I tried merging but with no success either.

Apologies if very basic, I have researched the problem but am very much a beginner.

Thanks

Here is one of the data frames, extracted from an excel spreadhseet


Solution

  • Say I have the following dataframes;

    df1=pd.DataFrame({'a':[1,2,3,4,5,6], 'b':[6,7,8,9,9,0],'c':[6,7,8,9,9,0],'d':[6,7,8,9,9,0],'e':[6,7,8,9,9,0]})
    df2=pd.DataFrame({'a':[1,2,13,41,5,6], 'b':[61,7,83,9,9,60],'c':[61,7,83,9,9,60],'d':[61,7,83,9,9,60],'e':[61,7,83,9,9,60]})
    

    Set a common index(You must be careful though, make sure you set an index common among the datframes.In this case, I just reset them to make it start from 0 on wards)

    df1= df.iloc[0:3, 1:3]
    df1.reset_index(drop=True, inplace=True)
    df2=df.iloc[3:6, 1:3]
    df2.reset_index(drop=True, inplace=True)
    

    Do an inner concat

    result = pd.concat([df1, df2], axis=1, join='inner')
    result