[Python] Pandas: set all values that are <= 0 to the maximum value in a column by group, but...

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

  1. Stack

    Stack Membro Participativo

    I am trying to set all values that are <= 0, by group, to the maximum value in that group, but only after the last positive value. That is, all values <=0 in the group that come before the last positive value must be ignored. Example:

    data = {'group':['A', 'A', 'A', 'A', 'A', 'B', 'B',
    'B', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C'],
    'value':[3, 0, 8, 7, 0, -1, 0, 9, -2, 0, 0, 2, 0, 5, 0, 1]}
    df = pd.DataFrame(data)
    df

    group value
    0 A 3
    1 A 0
    2 A 8
    3 A 7
    4 A 0
    5 B -1
    6 B 0
    7 B 9
    8 B -2
    9 B 0
    10 B 0
    11 C 2
    12 C 0
    13 C 5
    14 C 0
    15 C 1


    and the result must be:

    group value
    0 A 3
    1 A 0
    2 A 8
    3 A 7
    4 A 8
    5 B -1
    6 B 0
    7 B 9
    8 B 9
    9 B 9
    10 B 9
    11 C 2
    12 C 0
    13 C 5
    14 C 0
    15 C 1


    Thanks to advise

    Continue reading...

Compartilhe esta Página