2014-10-28 19 views
1

以下numpy片段將返回輸入數組的cumsum,每次遇到NaN時都會重置。如果超過極限,則重置cumsum(python)

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) 

以類似的方式,我怎麼可以計算重置如果cumsum是在使用矢量大熊貓或numpy的操作一些價值cumsum?

E.g.對於極限= 5,in = [1,1,1,1,1,1,1,1,1,1],out = [1,2,3,4,5,1,2,3,4, 5]

回答

2

如果你的數組中的數字都是積極的,它可能是最簡單的使用cumsum(),然後將模運算符:

>>> 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]) 

然後,您可以設置任何零個值回限制,以獲得所需的陣列:

>>> x[x == 0] = limit 
>>> x 
array([1, 2, 3, 4, 5, 1, 2, 3, 4, 5]) 

下面是使用熊貓一個可能的一般的解決方案0方法。 (我沒有測試它廣泛...)

首先定義修改cumsum功能:

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 

應用功能的陣列是這樣的:

>>> pd.expanding_apply(a, lambda x: cumsum_limit(x)) 
array([ 1., 2., 3., 4., 5., 1., 2., 3., 4., 5.]) 

這裏的應用功能到另一個更有趣的系列:

>>> 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