pandas - merging with missing values

烈酒焚心 提交于 2019-12-01 15:46:49

You could exclude values from bar (and indeed foo if you wanted) where id is null during the merge. Not sure it's what you're after, though, as they are sliced out.

(I've assumed from your left join that you're interested in retaining all of foo, but only want to merge the parts of bar that match and are not null.)

foo.merge(bar[pd.notnull(bar.id)], how='left', on='id')

Out[11]: 
id   x   y   z
0    a   1   2   3
1    b   4   5 NaN
2    c   7   8   9
3  NaN  10  11 NaN

if do not need NaN in both left and right DF, use

pd.merge(foo.dropna(), bar.dropna(), how='left', on='id')

else if need NaN in left DF, use

pd.merge(foo, bar.dropna(), how='left', on='id')

If You want to preserve the NaNs from both tables without slicing them out, you could use the outer join method as follows:

pd.merge(foo, bar.dropna(), how='outer', on='id')

It basically returns the union of foo and bar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!