代码之家  ›  专栏  ›  技术社区  ›  jpp

选择熊猫中ID相同但值不同的行

  •  1
  • jpp  · 技术社区  · 6 年前

    ID1         ID2      Value
    1209345     1203     2
    1209345     1204     3 <-----
    1209345     1205     4
    1209345     1203     2
    1209345     1204     7 <-----
    1209346     1203     1
    1209347     1204     5
    

    我有 ID1 相应地,我有多个 ID2 用值映射。我需要找到所有条目 ID1 小精灵 匹配,但值不同。

    我当前的代码统计 ID1 小精灵 ,但不说明唯一 Value 对于每个组合:

    print(df.groupby(['ID1', 'ID2']).size())
    
    ID1      ID2 
    1209345  1203    2
             1204    2
             1205    1
    1209346  1203    1
    1209347  1204    1
    dtype: int64
    

    注: 这个问题是为@rohitgirdhar发布的,他删除了他的 original question . 我发布的解决方案不一定是唯一或最好的解决方案;鼓励其他答案。

    2 回复  |  直到 6 年前
        1
  •  4
  •   jezrael    6 年前

    你可以过滤 nunique transform :

    df = df[df.groupby(['ID1', 'ID2'])['Value'].transform('nunique') > 1]
    
    print (df)
           ID1   ID2  Value
    1  1209345  1204      3
    4  1209345  1204      7
    
        2
  •  1
  •   jpp    6 年前

    一种方法是 groupby set ,筛选生成的序列,然后通过以下组合筛选原始数据帧: ID1 和; ID2 :

    grps = df.groupby(['ID1', 'ID2'])['Value'].apply(set)
    filtered = grps[grps.map(len) > 1].index
    
    res = df[df.set_index(['ID1', 'ID2']).index.isin(filtered)]
    
    print(res)
    
           ID1   ID2  Value
    1  1209345  1204      3
    4  1209345  1204      7