根据第二个数据框的匹配列更新 pandas 数据框 [英] Update pandas dataframe based on matching columns of a second dataframe

查看:61
本文介绍了根据第二个数据框的匹配列更新 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个熊猫数据框( df_1 df_2 ),它们具有相同的列,但是在一个数据框( df_1 )中,有些值是一个列丢失.因此,我只想填充 df_2 中的那些缺失值,但前提是两列的值匹配.

I have two pandas dataframes (df_1, df_2) with the same columns, but in one dataframe (df_1) some values of one column are missing. So I want to fill in those missing values from df_2, but only when the the values of two columns match.

这是我的数据如下所示的一个小例子:

Here is a little example what my data looks like:

df_1:

df_2:

我尝试使用以下方法添加缺少的值:

I tried to add the missing values with:

df_1.update(df_2, overwrite=False)

但是问题是,即使只有一列匹配,它也会填写值.当列"housenumber"和"street"匹配时,我想填写该值.

But the problem is, that it will fill in the values, even when just one column matches. I want to fill in the value when the columns "housenumber" AND "street" matches.

推荐答案

我认为您需要

I think you need set_index for Multiindex in both DataFrames and then combine_first or fillna:

df1 = df_1.set_index(["housenumber", "street"])
df2 = df_2.set_index(["housenumber", "street"])

df = df1.combine_first(df2).reset_index()


df = df1.fillna(df2).reset_index()

这篇关于根据第二个数据框的匹配列更新 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆