如果超出限制,则重置累积金额(python) [英] Reset cumsum if over limit (python)
问题描述
以下numpy代码段将返回输入数组的总和,每次遇到NaN都会重置该总和.
The following numpy snippet will return a cumsum of the input array, which resets every time a NaN is encountered.
v = np.array([1., 1., 1., np.nan, 1., 1., 1., 1., np.nan, 1.])
n = np.isnan(v)
a = ~n
c = np.cumsum(a)
d = np.diff(np.concatenate(([0.], c[n])))
v[n] = -d
result = np.cumsum(v)
以类似的方式,如果使用矢量化的熊猫或numpy操作,如果某个总和超过某个值,我该如何计算该总和重置?
In a similar fashion, how can I calculate a cumsum which resets if the cumsum is over some value using vectorized pandas or numpy operations?
例如对于限制= 5,输入= [1,1,1,1,1,1,1,1,1,1],输出= [1,2,3,4,5,1,2,3,4, 5]
E.g. for limit = 5, in = [1,1,1,1,1,1,1,1,1,1], out = [1,2,3,4,5,1,2,3,4,5]
推荐答案
如果数组中的数字都是正数,则使用cumsum()
然后使用取模运算符可能最简单:
If the numbers in your array are all positive, it is probably simplest to use cumsum()
and then the modulo operator:
>>> a = np.array([1,1,1,1,1,1,1,1,1,1])
>>> limit = 5
>>> x = a.cumsum() % limit
>>> x
array([1, 2, 3, 4, 0, 1, 2, 3, 4, 0])
然后您可以将任何零值设置回限制以获取所需的数组:
You can then set any zero values back to the limit to get the desired array:
>>> x[x == 0] = limit
>>> x
array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5])
这是使用Pandas的expanding_apply
方法的一种可能的通用解决方案. (我尚未对其进行广泛的测试...)
Here's one possible general solution using Pandas' expanding_apply
method. (I've not tested it extensively...)
首先定义一个修改后的cumsum
函数:
First define a modified cumsum
function:
import pandas as pd
def cumsum_limit(x):
q = np.sum(x[:-1])
if q > 0:
q = q%5
r = x[-1]
if q+r <= 5:
return q+r
elif (q+r)%5 == 0:
return 5
else:
return (q+r)%5
a = np.array([1,1,1,1,1,1,1,1,1,1]) # your example array
像下面这样将函数应用于数组:
Apply the function to the array like this:
>>> pd.expanding_apply(a, lambda x: cumsum_limit(x))
array([ 1., 2., 3., 4., 5., 1., 2., 3., 4., 5.])
以下是应用于另一个更有趣的系列的功能:
Here's the function applied to another more interesting Series:
>>> s = pd.Series([3, -8, 4, 5, -3, 501, 7, -100, 98, 3])
>>> pd.expanding_apply(s, lambda x: cumsum_limit(x))
0 3
1 -5
2 -1
3 4
4 1
5 2
6 4
7 -96
8 2
9 5
dtype: float64
这篇关于如果超出限制,则重置累积金额(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!