Python 用另一个数据集中的列中的值填充空值

Python 用另一个数据集中的列中的值填充空值,python,pandas,Python,Pandas,我有两个这样的数据集: 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包含一列,其值位于相同索引上,其中df1为null 我希望得到以下结果: df1.head(5) category cost 0 1 33.0 1 1 33.0 2 2 1

我有两个这样的数据集:

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包含一列,其值位于相同索引上,其中df1为null

我希望得到以下结果:

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
因此,用df2中相同索引上的值填充df1中的成本列

按索引分配:

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

谢谢你,我尝试了类似于
df1['cost'].loc[df1['cost'].isnull()]
的东西,但没有work@adamlowlife是的,我认为利用
fillna
在这里是最干净的。