【发布时间】:2021-11-11 11:23:36
【问题描述】:
我曾经对两个一维数组执行外减法如下,以接收包含所有减法对的单个二维数组:
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”的解决方案来执行此操作?
【问题讨论】:
标签: python python-3.x numpy