Skip to main content
 首页 » 编程设计

python之pandas combine_first 与特定的索引列

2025年05月04日8zhwl

我正在尝试在 pandas 中加入两个数据框以实现以下行为:我想加入指定的列,但要加入它以便不会将冗余列添加到数据框中。这类似于 combine_first 除了 combine_first 似乎没有采用索引列可选参数。示例:

# combine df1 and df2 based on "id" column 
df1 = pandas.merge(df2, how="outer", on=["id"]) 

上面的问题是 df1/df2 共有的列除了“id”之外将被添加到 df1 两次(带有 _x,_y 前缀)。我该怎么做:

# Do outer join from df2 to df1, matching items by "id" but not adding 
# columns that are redundant (df1 takes precedence if the values disagree) 
df1.combine_first(df2, on=["id"]) 

如何做到这一点?

请您参考如下方法:

如果您尝试将 df2 中的列合并到 df1 中,同时排除任何冗余列,则以下操作应该有效。

df1.set_index("id", inplace=True) 
df2.set_index("id", inplace=True) 
df3 = df1.merge(df2.ix[:,df2.columns-df1.columns], left_index=True, right_index=True, how="outer") 

但是,这显然不会用 df2 中的值更新 df1 中的 任何 值,因为它只会引入非冗余列。但是既然你说 df1 将优先处理任何不同意的值,也许这会成功吗?