Calculate new value based on decreasing value

前端 未结 4 1800
抹茶落季
抹茶落季 2020-12-20 12:26

Problem:

What\'d I like to do is step-by-step reduce a value in a Series by a continuously decreasing base figure.

I\'m not sur

4条回答
  •  醉酒成梦
    2020-12-20 12:36

    This is probably not so performant but at the moment this is a Pandas way of doing this using rolling_apply:

    In [53]:
    
    ALLOWANCE = 100
    def reduce(x):
        global ALLOWANCE
        # short circuit if we've already reached 0
        if ALLOWANCE == 0:
            return x
        val = max(0, x - ALLOWANCE)
        ALLOWANCE = max(0, ALLOWANCE - x)
        return val
    
    pd.rolling_apply(values, window=1, func=reduce)
    Out[53]:
    0     0
    1     0
    2    20
    3    30
    dtype: float64
    

    Or more simply:

    In [58]:
    
    values.apply(reduce)
    Out[58]:
    0     0
    1     0
    2    20
    3    30
    dtype: int64
    

提交回复
热议问题