Simd
Simd

Reputation: 21353

How to concat dataframes so missing values are set to NaN

I have two dataframes df1 and df2. Here is a toy example so show my question. df1 looks like

col1 col2
1    2
0    7

df2 looks like

col1 col3
9    2
5    3

I would like to do pd.concat([df1,df2]) but in such a way that the result is:

col1 col2 col3
1    2    NaN
0    7    Nan
9    NaN  2
5    NaN  3

Is there a way to do this?

Upvotes: 0

Views: 90

Answers (1)

Ankur Sinha
Ankur Sinha

Reputation: 6677

import pandas as pd

df1 = pd.DataFrame()
df1['col1'] = [1, 0]
df1['col2'] = [2, 7]

df2 = pd.DataFrame()
df2['col1'] = [9, 5]
df2['col3'] = [5, 3]

x = df1.append(df2)

Output:

   col1  col2  col3
0     1   2.0   NaN
1     0   7.0   NaN
0     9   NaN   5.0
1     5   NaN   3.0

Upvotes: 1

Related Questions