根据递减值计算新值 [英] Calculate new value based on decreasing value

查看:74
本文介绍了根据递减值计算新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

我想做的是通过不断减小的基础图形逐步减小Series中的值.

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

我不确定这个用词是什么-我确实认为我可以对cumsumdiff做一些事情,但我认为我正在带领自己去追赶鹅...

I'm not sure of the terminology for this - I did think I could do something with cumsum and diff but I think I'm leading myself on a wild goose chase there...

起始代码:

import pandas as pd

ALLOWANCE = 100
values = pd.Series([85, 10, 25, 30])

所需的输出:

desired = pd.Series([0, 0, 20, 30])

理论价格:

ALLOWANCE的底数开始-Series中的每个值都减去剩余量,这是津贴额本身,因此发生以下步骤:

Starting with a base of ALLOWANCE - each value in the Series is reduced by the amount remaining, as is the allowance itself, so the following steps occur:

  • 从100开始,我们可以完全删除85,使其变为0,现在剩下15作为ALLOWANCE
  • 下一个值是10,我们仍然有15可用,因此它再次变为0,剩下5.
  • 下一个值是25-我们只剩下5,所以它变成了20,现在我们没有更多的余量了.
  • 下一个值是30,并且由于没有余量,因此该值仍保持为30.
  • Start with 100, we can completely remove 85 so it becomes 0, we now have 15 left as ALLOWANCE
  • The next value is 10 and we still have 15 available, so this becomes 0 again and we have 5 left.
  • The next value is 25 - we only have 5 left, so this becomes 20 and now we have no further allowance.
  • The next value is 30, and since there's no allowance, the value remains as 30.

推荐答案

按照最初对cumsumdiff的想法,您可以编写:

Following your initial idea of cumsum and diff, you could write:

>>> (values.cumsum() - ALLOWANCE).clip_lower(0).diff().fillna(0)
0     0
1     0
2    20
3    30
dtype: float64

这是values的总和减去津贴.负值将被裁剪为零(因为直到我们超支了额度之前我们才关心数字).从那里,您可以计算出差异.

This is the cumulative sum of values minus the allowance. Negative values are clipped to zeros (since we don't care about numbers until we have overdrawn our allowance). From there, you can calculate the difference.

但是,如果第一个值可能大于允许值,则最好采用以下两行形式的变化:

However, if the first value might be greater than the allowance, the following two-line variation is preferred:

s = (values.cumsum() - ALLOWANCE).clip_lower(0)
desired = s.diff().fillna(s)

这将用第一个值-余量"值填充第一个NaN值.因此,在ALLOWANCE降低到75的情况下,它返回desired作为Series([10, 10, 25, 30]).

This fills the first NaN value with the "first value - allowance" value. So in the case where ALLOWANCE is lowered to 75, it returns desired as Series([10, 10, 25, 30]).

这篇关于根据递减值计算新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆