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

如何筛选属于具有多个成员的组的所有行?

  •  1
  • Cleb  · 技术社区  · 7 年前

    我有一个类似的问题 this one .

    我有这样一个数据帧:

    import pandas as pd
    
    df = pd.DataFrame({'A': list(range(7)),
                       'B': ['a', 'b', 'a', 'c', 'c', 'b', 'b'],
                       'C': ['x', 'x', 'x', 'z', 'z', 'y', 'x']}
                      )
    
       A  B  C
    0  0  a  x
    1  1  b  x
    2  2  a  x
    3  3  c  z
    4  4  c  z
    5  5  b  y
    6  6  b  x
    

    我想 groupby B C 然后从中选择所有行 df 组大小大于1的。

    我的 预期结果 可能是

       A  B  C
    0  0  a  x
    1  1  b  x
    2  2  a  x
    3  3  c  z
    4  4  c  z
    6  6  b  x
    

    所以我可以做

    gs_bool = df.groupby(['B', 'C']).size() > 1
    

    这给了

    B  C
    a  x     True
    b  x     True
       y    False
    c  z     True
    dtype: bool
    

    现在我该如何反馈给 测向 ?

    2 回复  |  直到 7 年前
        1
  •  2
  •   jezrael    7 年前

    你真的很需要 GroupBy.transform :

    gs_bool = df.groupby(['B', 'C'])['B'].transform('size') > 1
    print (gs_bool)
    0     True
    1     True
    2     True
    3     True
    4     True
    5    False
    6     True
    Name: B, dtype: bool
    

    df = df[gs_bool]
    print (df)
       A  B  C
    0  0  a  x
    1  1  b  x
    2  2  a  x
    3  3  c  z
    4  4  c  z
    6  6  b  x
    
        2
  •  2
  •   MaxU - stand with Ukraine    7 年前

    IIUC:

    In [38]: df.groupby(['B','C']).filter(lambda x: len(x) > 1)
    Out[38]:
       A  B  C
    0  0  a  x
    1  1  b  x
    2  2  a  x
    3  3  c  z
    4  4  c  z
    6  6  b  x