0

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?

Simd
  • 19,447
  • 42
  • 136
  • 271

1 Answers1

1
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
Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73
  • Thank you. Looks like I made a silly mistake missing the []. How is append different from concat? – Simd Jun 19 '18 at 13:29
  • 1
    This would be a good read: https://stackoverflow.com/questions/15819050/pandas-dataframe-concat-vs-append – Ankur Sinha Jun 19 '18 at 13:34
  • Another link to understand append, concatenation and merge concepts in Pandas: https://pandas.pydata.org/pandas-docs/stable/merging.html – Ankur Sinha Jun 19 '18 at 13:34