Home > Net >  Append two pandas DataFrame with different shapes
Append two pandas DataFrame with different shapes

Time:04-14

I have two pandas DataFrame of different shapes that I am trying to append. df2 is a subset of columns in df1. In the Final resultant DataFrame, I am looking for all columns in df1 and columns from df2. For missing columns, the values must be NaN.

df1 = pd.DataFrame({
                    'c0': [0, 0, 0],
                    'c1': [3, 4, 5],
                    'c2': [6, 7, 8],
                    'c3': [3, 3, 3]
                  })

df1 = pd.DataFrame({
                    'c1': [6, 7, 8],
                    'c2': [9, 10, 11],
                  })


c0   c1  c2  c3

0    3   6   3
0    4   7   3
0    5   8   3
NaN  6   9   NaN
NaN  7   10  NaN
NaN  8   11  NaN

            

CodePudding user response:

try

df1.append(df2)
Out[2]: 
    c0  c1  c2   c3
0  0.0   3   6  3.0
1  0.0   4   7  3.0
2  0.0   5   8  3.0
0  NaN   6   9  NaN
1  NaN   7  10  NaN
2  NaN   8  11  NaN

CodePudding user response:

What you are looking for is merge from Pandas :

df1.merge(df2, how="outer")
Out[3]: 
    c0  c1  c2   c3
0  0.0   3   6  3.0
1  0.0   4   7  3.0
2  0.0   5   8  3.0
3  NaN   6   9  NaN
4  NaN   7  10  NaN
5  NaN   8  11  NaN

You can find more documentation on how merge works here

  • Related