我曾经对两个一维数组执行外部减法,如下所示,以接收包含所有减法对的单个二维数组:
import numpy as np
a = np.arange(5)
b = np.arange(3)
result = np.subtract.outer(a, b)
assert result.shape == (5, 3)
assert np.all(result == np.array([[aa - bb for bb in b] for aa in a ])) # no rounding errors
现在状态空间切换到二维,我想执行相同的操作,但只对数组 A 和 B 的最后一个轴上的两个值执行每次减法:
import numpy as np
A = np.arange(5 * 2).reshape(-1, 2)
B = np.arange(3 * 2).reshape(-1, 2)
result = np.subtract.outer(A, B)
# Obviously the following does not hold, because here we have got all subtractions, therefore the shape (5, 2, 3, 2)
# I would like to exchange np.subtract.outer such that the following holds:
# assert result.shape == (5, 3, 2)
expected_result = np.array([[aa - bb for bb in B] for aa in A ])
assert expected_result.shape == (5, 3, 2)
# That's what I want to hold:
# assert np.all(result == expected_result) # no rounding errors
是否有执行此操作的“仅限 numpy”的解决方案?
最佳答案
您可以将 A
扩展/ reshape 为 (5, 1, 2) 并将 B
扩展/ reshape 为 (1, 3, 2) 并让广播完成工作:
A[:, None, :] - B[None, :, :]
关于python - 如何在numpy中沿轴执行外减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69927457/