pandas combine_first与特定的索引列?

时间:2013-03-28 01:02:00

标签: python pandas

我正在尝试在pandas中连接两个数据帧以产生以下行为:我想在指定的列上加入,但是要使用它,所以不会将冗余列添加到数据帧中。这类似于combine_first,除了combine_first似乎没有采用索引列可选参数。例如:

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

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

# 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"])

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

如果您尝试将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")

但是,显然不会使用df1中的df2更新来自df1任何值,因为它只会引入非冗余列。但既然你说{{1}}会优先考虑任何不同意的价值,那么这可能会有所帮助吗?