Calculate new value based on decreasing value

前端 未结 4 1798
抹茶落季
抹茶落季 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:45

    Your idea with cumsum and diff works. It doesn't look too complicated; not sure if there's an even shorter solution. First, we compute the cumulative sum, operate on that, and then go back (diff is kinda sorta the inverse function of cumsum).

    import math
    
    c = values.cumsum() - ALLOWANCE
    # now we've got [-15, -5, 20, 50]
    c[c < 0] = 0 # negative values don't make sense here
    
    # (c - c.shift(1)) # <-- what I had first: diff by accident
    
    # it is important that we don't fill with 0, in case that the first
    # value is greater than ALLOWANCE
    c.diff().fillna(math.max(0, values[0] - ALLOWANCE))
    

提交回复
热议问题