close

how to concat two data frames with different column names in pandas? – python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about how to concat two data frames with different column names in pandas? – python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

how to concat two data frames with different column names in pandas? – python

  1. how to concat two data frames with different column names in pandas? – python

    Use numpy to concatenate the dataframes, so you don't have to rename all of the columns (or explicitly ignore indexes). np.concatenate also works on an arbitrary number of dataframes.

  2. concat two data frames with different column names in pandas? – python

    Use numpy to concatenate the dataframes, so you don't have to rename all of the columns (or explicitly ignore indexes). np.concatenate also works on an arbitrary number of dataframes.

Method 1

Just use concat and rename the column for df2 so it aligns:

In [92]:
pd.concat([df1,df2.rename(columns={'b':'a'})], ignore_index=True)

Out[92]:
    a   x   y
0   1   4   7
1   2   5   8
2   3   6   9
3  10  13  16
4  11  14  17
5  12  15  18

similarly you can use merge but you’d need to rename the column as above:

In [103]:
df1.merge(df2.rename(columns={'b':'a'}),how='outer')

Out[103]:
    a   x   y
0   1   4   7
1   2   5   8
2   3   6   9
3  10  13  16
4  11  14  17
5  12  15  18

Method 2

Use numpy to concatenate the dataframes, so you don’t have to rename all of the columns (or explicitly ignore indexes). np.concatenate also works on an arbitrary number of dataframes.

df = pd.DataFrame( np.concatenate( (df1.values, df2.values), axis=0 ) )
df.columns = [ 'a', 'x', 'y' ]
df

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read