【问题标题】:How to do "(df1 & not df2)" dataframe merge in pandas?如何在熊猫中进行“(df1&not df2)”数据框合并?
【发布时间】:2015-12-17 00:29:06
【问题描述】:

我有 2 个 Pandas 数据帧 df1 和 df2,它们具有公共列/键 (x,y)。

我想合并对键 (x,y) 执行“(df1 & not df2)”类型的合并,这意味着我希望我的代码返回一个数据帧,其中包含仅在 df1 中且不包含 (x,y) 的行在df2中。

SAS 具有相同的功能

data final;
merge df1(in=a) df2(in=b);
by x y;
if a & not b;
run;

谁来优雅地在 pandas 中复制相同的功能? 如果我们可以在 merge() 中指定 how="left-right" 那就太好了。

【问题讨论】:

    标签: python join pandas merge dataframe


    【解决方案1】:

    我刚刚升级到 10 天前发布的 0.17.0 RC1 版本。 刚刚发现 pd.merge() 在这个新版本中有一个名为 indicator=True 的新参数,以实现这一点!!

    df=pd.merge(df1,df2,on=['x','y'],how="outer",indicator=True)
    df=df[df['_merge']=='left_only']
    

    indicator:向输出 DataFrame 添加一个名为 _merge 的列,其中包含有关每行来源的信息。 _merge 是分类类型,对于合并键仅出现在“左”数据帧中的观察,取值 left_only,对于合并键仅出现在“右”数据帧中的观察,如果观察的合并键在两者中都找到,则两者都取值.

    http://pandas-docs.github.io/pandas-docs-travis/merging.html#database-style-dataframe-joining-merging

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-20
    • 2021-06-21
    • 2021-04-26
    • 2019-12-02
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    相关资源
    最近更新 更多