python - Cumsum reset at NaN -


if have pandas.core.series.series named ts of either 1's or nan's this:

3382   nan 3381   nan ... 3369   nan 3368   nan ... 15     1 10   nan 11     1 12     1 13     1 9    nan 8    nan 7    nan 6    nan 3    nan 4      1 5      1 2    nan 1    nan 0    nan 

i calculate cumsum of serie should reset (set zero) @ location of nans below:

3382   0 3381   0 ... 3369   0 3368   0 ... 15     1 10     0 11     1 12     2 13     3 9      0 8      0 7      0 6      0 3      0 4      1 5      2 2      0 1      0 0      0 

ideally have vectorized solution !

i ever see similar question matlab : matlab cumsum reset @ nan?

but don't know how translate line d = diff([0 c(n)]);

a simple numpy translation of matlab code this:

import numpy np  v = np.array([1., 1., 1., np.nan, 1., 1., 1., 1., np.nan, 1.]) n = np.isnan(v) = ~n c = np.cumsum(a) d = np.diff(np.concatenate(([0.], c[n]))) v[n] = -d np.cumsum(v) 

executing code returns result array([ 1., 2., 3., 0., 1., 2., 3., 4., 0., 1.]). solution valid original one, maybe come better if isn't sufficient purposes.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -