Take the sum of a numpy array based on a logical array

I have two numpy arrays prodsandindex

prods = np.asarray([ 0.5 ,  0.25,  1.98,  2.4 ,  2.1 ,  0.6 ])
index = np.asarray([False,  True,  True, False, False,  True], dtype=bool)

I need to calculate the sum of the values ​​in an array prodsusing an array index. The output I want

res = [0.75, 1.98, 5.1]

A first array Truein indexprecedes a False, so I take the first two elements of prods(. 5, .25) and sums them (0.75). The second one Truein the index does not have the previous one False(since it is preceded by a True, it Falseis not taken into account in the position of zero), so I simply output 1.98 in this case. The third is Truepreceded by two False, so I take these values ​​from the array prods(2.4.2.1.0.6) and summarize them. Any ideas on how to do this?

I basically need something like np.cumsum, but I need to return the cumulative amount every time it Trueoccurs in the index, and reset is the total value of the sum to zero.

+2
source share
1 answer

You can use np.splitand using np.whereyour array indexas positions for splitting:

>>> [arr.sum() for arr in np.split(prods, np.where(index)[0]+1)[:-1]]
[0.75, 1.98, 5.0999999999999996]

The latter is not exactly 5.1because of the precision floating point. If you do not want to use Fractionor Decimal, you cannot do anything about it.


You can also use np.add.reduceathere:

>>> np.add.reduceat(prods, np.append([0], (np.where(index)[0]+1)[:-1]))
array([ 0.75,  1.98,  5.1 ])
+3
source

Source: https://habr.com/ru/post/1683517/


All Articles