[Numpy-discussion] Is there a way to reset an accumulate function?
Robert Kern
robert.kern@gmail....
Wed Oct 24 03:47:51 CDT 2012
On Tue, Oct 23, 2012 at 6:11 PM, Cera, Tim <tim@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?
def nancumsum(x):
nans = np.isnan(x)
x = np.array(x)
x[nans] = 0
reset_idx = np.zeros(len(x), dtype=int)
reset_idx[nans] = np.arange(len(x))[nans]
reset_idx = np.maximum.accumulate(reset_idx)
cumsum = np.cumsum(x)
cumsum = cumsum - cumsum[reset_idx]
return cumsum
--
Robert Kern
More information about the NumPy-Discussion
mailing list