numpy - Reset cumsum if over limit (python) -


The following oval snippet will return a cumsum of the input array, which each time encounters a NaN.

  v = np.array ([1., 1., 1., np.nan, 1., 1., 1., 1., N. P. Annan, 1.]) N = np.isnan (v) a = ~ nc = np.cumsum (a) d = np.diff (np.concatenate (([.], C [n]))) v [n] = -d result = Np.cumsum (v)  

In a similar way, how can I calculate a cumsum using cumsum vectorized pandas or numpy operations to exceed some value?

For example, for range = 5, = [1,1,1,1,1,1,1,1] in, out = [1,2,3,4,5] , 1,2,3,4,5]

If the numbers in your array are all positive, then This is probably Cumsum () and then the modulo operator:

  & gt; & Gt; & Gt; A = np.array ([1,1,1,1,1,1,1,1,1,1]) & gt; & Gt; & Gt; Limit = 5> gt; & Gt; & Gt; X = a.cumsum ()% range & gt; & Gt; & Gt; X array ([1, 2, 3, 4, 0, 1, 2, 3, 4, 0])  

Then you can set back any zero value to the limit Desired array:

  & gt; & Gt; & Gt; X [x == 0] = range> & gt; & Gt; X array ([1, 2, 3, 4, 5, 1, 2, 3, 4, 5])  

Here is a common solution using Pandya ' Expanding_apply method (I have not tested it extensively ...)

Firstly define a modified code function:

< Pre> import pandas as pd def cumsum_limit x): q = np.sum (x [: - 1]) if q> If q + r = 5: return q + r elif (q + r)% 5 == 0: return 5 and: return (q + r): 0: q = q% 5 r = x [-1] % 5 a = np.array ([1,1,1,1,1,1,1,1]) # Apply your example array

to the array in the function By way:

  & gt; & Gt; & Gt; Pd.expanding_apply (a, lambda x: cumsum_limit (x)) array ([1., 2., 3., 4, 5., 1., 2., 3., 4., 5.])  

Here is a function applied to another interesting series:

  & gt; & Gt; & Gt; S = pd.Series ([3, -8, 4, 5, -3, 501, 7, -100, 98, 3]) & gt; & Gt; & Gt; Pd.expanding_apply (s, lambda x: cumsum_limit (x)) 0 3 1 -5 2 -13 4 4 1 5 2 6 4 7-9 8 8 9 5 dtype: float64  

Comments

Popular posts from this blog

java - Can't add JTree to JPanel of a JInternalFrame -

javascript - data.match(var) not working it seems -

javascript - How can I pause a jQuery .each() loop, while waiting for user input? -