通过利用
broadcasting
例如:
In [28]: (A[:, np.newaxis] - B).reshape(-1, A.shape[1])
Out[28]:
array([[ -9, -18, -27],
[ -999, -1998, -2997],
[ 11, 22, 5],
[ 90, 180, 270],
[ -900, -1800, -2700],
[ 110, 220, 302]])
或者,比
广播
,我们必须使用
numexpr
例如:
In [31]: A_3D = A[:, np.newaxis]
In [32]: import numexpr as ne
# pass the expression for subtraction as a string to `evaluate` function
In [33]: ne.evaluate('A_3D - B').reshape(-1, A.shape[1])
Out[33]:
array([[ -9, -18, -27],
[ -999, -1998, -2997],
[ 11, 22, 5],
[ 90, 180, 270],
[ -900, -1800, -2700],
[ 110, 220, 302]], dtype=int64)
另一种效率最低的方法是使用
np.repeat
和
np.tile
匹配两个阵列的形状。但是,请注意,这是
效率最低
选项,因为它使
副本
尝试匹配形状时。
In [27]: np.repeat(A, B.shape[0], 0) - np.tile(B, (A.shape[0], 1))
Out[27]:
array([[ -9, -18, -27],
[ -999, -1998, -2997],
[ 11, 22, 5],
[ 90, 180, 270],
[ -900, -1800, -2700],
[ 110, 220, 302]])