[Numpy-discussion] Is there a way to reset an accumulate function?
Tue Oct 23 14:12:26 CDT 2012
On 23 October 2012 13:11, Cera, Tim <email@example.com> 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 : 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
Out: array([ 10., 6., 3.])
Note that if the last element of a is nan, you get a final 0 in the result.
Post-doctoral research fellow
Neurobiology, University of Pittsburgh
More information about the NumPy-Discussion