How can I use a mod in an array using numpy

3202 views python
4

Let's say I have an array

a = ([6,8,10,13,15,18,21])

I have another array

b= ([2,5])

I want to return an array which gives me nonzero values of a%b. If any value in a mod any value in b equals zero, I don't want to return it.

c = ([13,21])

Using numpy.mod(a,b) returns

ValueError: operands could not be broadcast together with shapes

How can I execute this?

answered question

a[np.mod.outer(a, b).all(1)]?

1 Answer

7

The problem refers to the fact that numpy cannot apply the np.mod operation on the arrays with the given shape, one solution is to reshape, for example:

import numpy as np

a = np.array([6, 8, 10, 13, 15, 18, 21]).reshape((-1, 1))
b = np.array([2, 5])

print(a[np.mod(a, b).all(1)].reshape(-1))

Output

[13 21]

Note that you need to reshape back to obtain the requested output. The best solution is the one proposed by @PaulPanzer:

import numpy as np

a = np.array([6, 8, 10, 13, 15, 18, 21])
b = np.array([2, 5])

print(a[np.mod.outer(a, b).all(1)])

Output

[13 21]

Further

  1. On numpy broadcasting see 1 and 2.
  2. On outer.

posted this

Have an answer?

JD

Please login first before posting an answer.