András Czeitner
András Czeitner

Reputation: 63

How to make the union of two df that have different column names

In pandas i have two dataframe both has 4 column but different column name. Eventhough the column names differ they actually contains the same info.

If i try to concat them pandas make a 8 column df, but i want it to stay for column.

df1
     A B C D
     1 2 3 4
     5 6 7 8

df2
     D  F  G  H
     7  8  9 10
    11 12 13 14

The result I want is : DF3

 A  B   C   D
 1  2   3   4
 5  6   7   8
 7  8   9   10
 11 12  13  14

Could you please let me know how to make the union of DF1 and DF2 like this ?

Thanks

Upvotes: 1

Views: 1288

Answers (4)

AmineBTG
AmineBTG

Reputation: 697

Try the below:

df2.columns = df1.columns
df3 = df1.append(df2)

Upvotes: 3

blackraven
blackraven

Reputation: 5627

Rename the column names of df2 to be the same as df1, and apply .append(). Finally reset the index.

df2.columns = df1.columns
df3 = df1.append(df2).reset_index(drop=True)

Upvotes: 1

Joe Thor
Joe Thor

Reputation: 1260

You could rename the columns in df2 to match df1, then append the dataframe

names = df1.columns.values.tolist()

df2 = df2.rename(columns = names, inplace = True)

df3 = df1.append(df2)

Upvotes: 1

BENY
BENY

Reputation: 323326

Let us try

out = pd.concat([df1, df2.rename(columns = dict(zip(df2.columns, df1.columns)))])
Out[16]: 
    A   B   C   D
0   1   2   3   4
1   5   6   7   8
0   7   8   9  10
1  11  12  13  14

Upvotes: 2

Related Questions