Home > OS >  How to merge two dataframes row wise in pandas
How to merge two dataframes row wise in pandas

Time:11-22

I want to concatenate my two dataframes (df1 and df2) row wise to obtain dataframe (df3) in below format:

1st row of df3 have 1st row of df1.

2nd row of df3 have 1st row of df2.

3rd row of df3 have 2nd row of df1.

4th row of df3 have 2nd row of df2. .. and so on

Any idea how can I do that?

Note- both dataframes have same column names

CodePudding user response:

A simple way would be modifying the index for dataframes before concatenation, then sort on it!

df1 = pd.DataFrame(

    {

        "A": ["A0", "A1", "A2", "A3"],

        "B": ["B0", "B1", "B2", "B3"],

        "C": ["C0", "C1", "C2", "C3"],

        "D": ["D0", "D1", "D2", "D3"],

    },

    index=[0, 2, 4, 6],

)



df2 = pd.DataFrame(

    {

        "A": ["A4", "A5", "A6", "A7"],

        "B": ["B4", "B5", "B6", "B7"],

        "C": ["C4", "C5", "C6", "C7"],

        "D": ["D4", "D5", "D6", "D7"],

    },

    index=[1, 3, 5, 7],

)
pd.concat((df1, df2)).sort_index(axis = 0)

output:

    A   B   C   D
0  A0  B0  C0  D0
1  A4  B4  C4  D4
2  A1  B1  C1  D1
3  A5  B5  C5  D5
4  A2  B2  C2  D2
5  A6  B6  C6  D6
6  A3  B3  C3  D3
7  A7  B7  C7  D7

CodePudding user response:

You can use pandas.concat, and sort_index:

df1 = pd.DataFrame({'col': list('AXYZ')})
df2 = pd.DataFrame({'col': list('EDCB')})

(pd.concat([df1, df2])
   .sort_index()
 )

Output:

  col
0   A
0   E
1   X
1   D
2   Y
2   C
3   Z
3   B
  • Related