kfmfe04
kfmfe04

Reputation: 15327

How to combine two dataframes (same shape, including NaN)?

I want to combine df1 and df2 to get df3.

df1 and df2 will have the exact same index and column (same shape), including some np.NaN. They will have no overlapping values (no ambiguity). Take the value if it's there in either one.

What is the most direct way to do this?

df1 = pd.DataFrame({'A': [1.0, np.NaN], 'B':[np.NaN, np.NaN]})
df2 = pd.DataFrame({'A': [np.NaN, np.NaN], 'B':[np.NaN, 0.0]})
df3 = pd.DataFrame({'A': [1.0, np.NaN], 'B':[np.NaN, 0.0]})

I've tried df1 + df2, df1 | df2, and looked into merge() but no luck.

Thanks in advance.

Edit

Suppose I do a replace(0,magicNumber) and then a replace(np.NaN, 0). Then I can add the two dataframes and then do a replace(magicNumber, 0). But this is very ugly, obfuscating code. If there's a cleaner, pandomic/pythonic solution, please do let me know. Thx.

Upvotes: 0

Views: 820

Answers (1)

SeaBean
SeaBean

Reputation: 23217

Use: df3 = df1.combine_first(df2)

See the document here

Upvotes: 1

Related Questions