[Python] Calculating a pct_change between 3 values in a pandas series, where one of more of...

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

  1. Stack

    Stack Membro Participativo

    Scenario: I have a pandas series that contains 3 values. These values can vary between nan, 0 and any value above zero. I am trying to get the pct_change among the series whenever possible.

    Examples:

    [0,nan,50]
    [0,0,0]
    [0,0,50]
    [nan,nan,50]
    [nan,nan,0]
    [0,0,nan]
    [0,nan,0]


    What I tried: from other SO questions I was able to come up with methods either trying to ignore the nan or shifting, but these can potentially yield a result with empty values. Ideally, if a result cannot be calculated, I would like to output a 0.

    Code tried:

    series_test = pd.Series([0,None,50])
    series_test.pct_change().where(series_test.notna()) # tested but gives only NaN or inf

    series_test.pct_change(fill_method=None)[series_test.shift(2).notnull()].dropna() # tested but gives empty result


    Question: What would be the correct way to approach this?

    Expected outputs:

    [0,nan,50] - 0 (undefined case)
    [0,0,0] - 0 (undefined case)
    [0,0,50] - 0 (undefined case)
    [nan,nan,50] - 0 (undefined case)
    [nan,nan,0] - 0 (undefined case)
    [0,0,nan] - 0 (undefined case)
    [0,nan,0] - 0 (undefined case)
    [1,nan,5] - 400%
    [0,1,5] - 400%
    [1,2,nan] - 100%
    [1,1.3,1.8] - 80%

    Continue reading...

Compartilhe esta Página