Search code examples
pandasdataframemergeconcatenation

Concatenate row values in Pandas DataFrame


I have a problem with Pandas' DataFrame Object. I have read first excel file and I have DataFrame like this: First DataFrame

And read second excel file like this: Second DataFrame

I need to concatenate rows and it should like this: Third DataFrame

I have code like this:

import pandas as pd
import numpy as np
x1 = pd.ExcelFile("x1.xlsx")
df1 = pd.read_excel(x1, "Sheet1")
x2 = pd.ExcelFile("x2.xlsx")
df2 = pd.read_excel(x2, "Sheet1")
result = pd.merge(df1, df2, how="outer")

The second df just follow the first df,how can I get the style with dataframe like the third one?


Solution

  • merge does not concatenate the dfs as you want, use append instead.

    ndf = df1.append(df2).sort_values('name')
    

    You can also use concat:

    ndf = pd.concat([df1, df2]).sort_values('name')