[Python] polars remember last value

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

  1. Stack

    Stack Membro Participativo

    I like to create indicators for stocks. For ewm_mean, diffences, cum_sum, when/than/otherwise works fine. But here is nut i can't crack. First step is to find the direction of the values.

    import polars as pl

    df = pl.DataFrame(
    {
    "index": [0,1,2,3,4,5,6,7,8,9,10,11],
    "hl": [float("nan"),float("nan"),-1,float("nan"),1,float("nan"),float("nan"),float("nan"),-1,float("nan"),-1,float("nan")],
    "thisresultwouldbefine": [float("nan"),float("nan"),-1,-1,1,1,1,1,-1,-1,-1,-1],
    }
    )
    print(df)

    df = df.with_columns(pl.col('hl').alias('result'))
    print(df)

    index hl thisresultwouldbefine
    0
    1
    2 -1.0 -1.0
    3 -1.0
    4 1.0 1.0
    5 1.0
    6 1.0
    7 1.0
    8 -1.0 -1.0
    9 -1.0
    10 -1.0 -1.0
    11 -1.0

    index not needed (only for discussion). hl are the giving values. thisresultwouldbefine should be the output. At index 2 hl is -1. This should be memorized for the next value until hl changed. At index 3 hl is NaN and result should be -1 furthermore. At index 4 hl is 1 and the result should be 1.

    Continue reading...

Compartilhe esta Página