Reputation: 63
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
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
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
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