如何使用 numpy 在数组中使用 mod

How can I use a mod in an array using numpy

假设我有一个数组

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

我还有另一个数组

b= ([2,5])

我想要 return 一个数组,它给我 a%b 的非零值。如果 a mod 中的任何值 b 中的任何值等于零,我不想 return 它。

c = ([13,21])

使用 numpy.mod(a,b) returns

ValueError: operands could not be broadcast together with shapes

我该如何执行?

问题是numpy无法对给定shape的数组进行np.mod操作,解决办法是reshape,例如:

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))

输出

[13 21]

请注意,您需要重新整形以获得请求的输出。最好的解决方案是由@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)])

输出

[13 21]

进一步

  1. 关于 numpy 广播,请参阅 1 and 2
  2. outer