[Python] What is the best way to filter the groups that have at least N rows that meets the...

Discussão em 'Python' iniciado por Stack, Março 27, 2025.

  1. Stack

    Stack Membro Participativo

    This is my DataFrame:

    import pandas as pd
    df = pd.DataFrame({
    'a': [10, 20, 30, 50, 50, 50, 4, 100],
    'b': [30, 3, 200, 25, 24, 31, 29, 2],
    'd': list('aaabbbcc')
    })


    Expected output:

    a b d
    0 10 30 a
    1 20 3 a
    2 30 200 a


    The grouping is by column d. I want to return the groups that have at least two instances of this mask

    m = (df.b.gt(df.a))


    This is what I have tried. It works but I wonder if there is a better/more efficient way to do it.

    out = df.groupby('d').filter(lambda x: len(x.loc[x.b.gt(x.a)]) >= 2)

    Continue reading...

Compartilhe esta Página