[Python] What is the best way to filter groups by conditionally checking the values of the...

Discussão em 'Python' iniciado por Stack, Setembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    This is my DataFrame:

    import pandas as pd
    df = pd.DataFrame(
    {
    'group': list('xxxxyyy'),
    'open': [100, 150, 200, 160, 300, 150, 170],
    'close': [105, 150, 200, 160, 350, 150, 170],
    'stop': [104, 104, 104, 104, 400, 400, 400]
    }
    )


    Expected output is returning group x based on the group column:

    group open close stop
    0 x 100 105 104
    1 x 150 150 104
    2 x 200 200 104
    3 x 160 160 104


    Logic:

    I want to check if df.stop.iloc[0] for each group is between df.open.iloc[0] and df.close.iloc[0]. And if it is between these two, I want to return that entire group.

    This is my attempt. It works but I think there is a better way to do it. Note that in the if clause, both conditions are needed to be checked.

    def func(df):
    s = df.stop.iloc[0]
    o = df.open.iloc[0]
    c = df.close.iloc[0]

    if (o <= s <= c) or (c <= s <= o):
    return df

    out = df.groupby('group').apply(func).reset_index(drop=True)

    Continue reading...

Compartilhe esta Página