Home > Back-end >  np.array reset cumsum at np.nan
np.array reset cumsum at np.nan

Time:09-30

I have a numpy array like this:

 np.array([1, 2, 3, 4, np.nan, 2, 4, np.nan, 5, 1, 2, 1, np.nan, 10])

I want to split it and sum.

Expected output:

np.array([10, 6, 9, 10])

Can someone help me please? Thanks.

CodePudding user response:

Copy and set nan to 0, and then use numpy.add.reduceat to sum:

>>> mask = np.isnan(ar)
>>> arr = np.where(mask, 0, ar)
>>> mask[0] = True
>>> np.add.reduceat(arr, mask.nonzero()[0])
array([10.,  6.,  9., 10.])

CodePudding user response:

One way of doing it...

# create array
arr=np.array([1, 2, 3, 4, np.nan, 2, 4, np.nan, 5, 1, 2, 1, np.nan, 10])
# find arguments where array elements are nan
argsnan=np.argwhere(np.isnan(arr)).flatten()
# split array into list of arrays
list_of_arrays = np.split(arr, argsnan)
# sum up with list comprehension
list_sum = [np.sum(arr[np.isfinite(arr)]) for arr in list_of_arrays]
  • Related