问题描述
问题:
我想做的是通过不断减小的基础图形逐步减小Series
中的值.
What'd I like to do is step-by-step reduce a value in a Series
by a continuously decreasing base figure.
我不确定这个用词是什么-我确实认为我可以对cumsum
和diff
做一些事情,但我认为我正在带领自己去追赶鹅...
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 becomes0
, we now have15
left asALLOWANCE
- The next value is
10
and we still have15
available, so this becomes0
again and we have5
left. - The next value is
25
- we only have5
left, so this becomes20
and now we have no further allowance. - The next value is
30
, and since there's no allowance, the value remains as30
.
推荐答案
按照最初对cumsum
和diff
的想法,您可以编写:
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])
.
这篇关于根据递减值计算新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!