Cumsum reset at NaN

后端 未结 4 1391
醉话见心
醉话见心 2020-11-27 05:21

If I have a pandas.core.series.Series named ts of either 1\'s or NaN\'s like this:

3382   NaN
3381   NaN
...
3369   NaN
3368   NaN
         


        
4条回答
  •  粉色の甜心
    2020-11-27 06:06

    A simple Numpy translation of your Matlab code is this:

    import numpy as np
    
    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
    np.cumsum(v)
    

    Executing this code returns the result array([ 1., 2., 3., 0., 1., 2., 3., 4., 0., 1.]). This solution will only be as valid as the original one, but maybe it will help you come up with something better if it isn't sufficient for your purposes.

提交回复
热议问题