[Numpy-discussion] Is there a way to reset an accumulate function?
Angus McMorland
amcmorl at gmail.com
Tue Oct 23 15:12:26 EDT 2012
On 23 October 2012 13:11, Cera, Tim <tim at cerazone.net> wrote:
> I have an array that is peppered throughout in random spots with 'nan'. I
> would like to use 'cumsum', but I want it to reset the accumulation to 0
> whenever a 'nan' is encountered. Is there a way to do this? Aside from a
> loop - which is what I am going to setup here in a moment.
How about this hackish solution, for a quick non-looping fix?
In [39]: a = np.array([1,2,3,4,np.nan,1,2,3,np.nan,3])
idx = np.flatnonzero(np.isnan(a))
a_ = a.copy()
a_[idx] = 0
np.add.reduceat(a_, np.hstack((0,idx)))
Out[39]: array([ 10., 6., 3.])
Note that if the last element of a is nan, you get a final 0 in the result.
Angus
--
AJC McMorland
Post-doctoral research fellow
Neurobiology, University of Pittsburgh
More information about the NumPy-Discussion
mailing list