How to sum each element in a numpy array divisible by 5 using vectorization?

I am looking for a vectorization method to sum all the elements of a numpy array that is evenly divisible by 5.

For example, if I have

test = np.array([1,5,12,15,20,22])

      

I want to return 40. I know about the np.sum method, but is there a way to do it using vectorization, given the condition X% 5 == 0?

+3


source to share


1 answer


We can use mask

matches boolean-indexing

to select these items and then simply sum them up, like this:

test[test%5==0].sum()

      



An example of a step by step start -

# Input array
In [48]: test
Out[48]: array([ 1,  5, 12, 15, 20, 22])

# Mask of matches
In [49]: test%5==0
Out[49]: array([False,  True, False,  True,  True, False], dtype=bool)

# Select matching elements off input
In [50]: test[test%5==0]
Out[50]: array([ 5, 15, 20])

# Finally sum those elements
In [51]: test[test%5==0].sum()
Out[51]: 40

      

+6


source







All Articles