Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two dataframes with same column names but different number of columns in pandas

I have two pandas dataframes

df1 = DataFrame([[0,123,321],[0,1543,432]], columns=['A', 'B','C'])
df2 = DataFrame([[1,124],[1,1544]], columns=['A', 'C'])

I want to merge these so that the new dataframe would look like below

A     |    B      |   C
0         123        321
0         1543       432
1         null       124
1         null       1544

I have tried using append and concat but nothing seems to work. Any help would be much appreciated.

like image 575
Falconic Avatar asked Apr 19 '16 17:04

Falconic


People also ask

How do I merge DataFrames with different number of columns?

It is possible to join the different columns is using concat() method. DataFrame: It is dataframe name. axis: 0 refers to the row axis and1 refers the column axis. join: Type of join.

How do I merge two DataFrames with different column names in pandas?

Different column names are specified for merges in Pandas using the “left_on” and “right_on” parameters, instead of using only the “on” parameter. Merging dataframes with different names for the joining variable is achieved using the left_on and right_on arguments to the pandas merge function.

Can you merge two DataFrames of different lengths pandas?

It can be done using the merge() method. Below are some examples that depict how to merge data frames of different lengths using the above method: Example 1: Below is a program to merge two student data frames of different lengths.


2 Answers

Concatenate the dataframes

import pandas as pd
pd.concat([df1,df2], axis=0)
   A     B     C
0  0   123   321
1  0  1543   432
0  1   NaN   124
1  1   NaN  1544
like image 79
Abbas Avatar answered Oct 01 '22 11:10

Abbas


from doc-ref ref try: df1.append(df2, ignore_index=True)

sample output:

    A     B     C
 0  0   123   321
 1  0  1543   432
 2  1   NaN   124
 3  1   NaN  1544
like image 45
Joshua Baboo Avatar answered Oct 01 '22 11:10

Joshua Baboo