adamlowlife
adamlowlife

Reputation: 239

Fill null values with values from a column in another dataset

I have 2 datasets like this:

df1.head(5)
 category cost
0   1   33.0
1   1   33.0
2   2   18.0
3   1   NaN
4   3   8.0
5   2   NaN

df2.head(2)
 cost
3 33.0
5 55.0

df2 contains one column with values on the same indexes, where df1 is null

I would like to do get this result:

df1.head(5)
 category cost
0   1   33.0
1   1   33.0
2   2   18.0
3   1   33.0
4   3   8.0
5   2   55.0

So fill the cost column in df1 by values in df2 on the same indexes

Upvotes: 2

Views: 144

Answers (1)

jpp
jpp

Reputation: 164813

fillna

Pandas assigns by index naturally:

df1['cost'] = df1['cost'].fillna(df2['cost'])

print(df1)

   category  cost
0         1  33.0
1         1  33.0
2         2  18.0
3         1  33.0
4         3   8.0
5         2  55.0

Upvotes: 3

Related Questions