[Python] Finding the last row that meets conditions of a mask

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    This is my dataframe:

    df = pd.DataFrame({'a': [20, 21, 333, 444], 'b': [20, 20, 20, 20]})


    I want to create column c by using this mask:

    mask = (df.a >= df.b)


    And I want to get the last row that meets this condition and create column c. The output that I want looks like this:

    a b c
    0 20 20 NaN
    1 21 20 NaN
    2 333 20 NaN
    3 444 20 x


    I tried the code below but it didn't work:

    df.loc[mask.cumsum().gt(1) & mask, 'c'] = 'x'

    Continue reading...

Compartilhe esta Página