Osiris
Osiris

Reputation: 1027

How to use join to fill missing values of a column - Python Pandas?

To be concrete, say we have two DataFrames:

df1:

date    A
12/1/14 3
12/2/14 NaN
12/3/14 2
12/2/14 NaN
12/4/14 NaN
12/6/14 5

df2:

        B
12/2/14 20
12/4/14 30

I want to do kind of a left outer join to fill the missing values in df1, and generate

df3:

date    A
12/1/14 3
12/2/14 20
12/3/14 2
12/2/14 20
12/4/14 30
12/6/14 5

Any efficient way to make it?

Upvotes: 2

Views: 643

Answers (1)

joris
joris

Reputation: 139302

You can use combine_first (only the columns names should match, therefore I first rename the column B in df2):

In [8]: df2 = df2.rename(columns={'B':'A'})

In [9]: df1.combine_first(df2)
Out[9]:
          A
12/1/14   3
12/2/14  20
12/2/14  20
12/3/14   2
12/4/14  30
12/6/14   5

Upvotes: 2

Related Questions