python - 如何在numpy中沿轴执行外减法

标签 python python-3.x numpy

我曾经对两个一维数组执行外部减法,如下所示,以接收包含所有减法对的单个二维数组:

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/

相关文章:

python - 为什么感知器学习算法不收敛?

python - 如何在 ubuntu 的 cronjob 中运行 pipenv?

python-3.x - 改变先知情节的特点

python - 有没有办法预先分析 Python 程序的命名冲突?

python - 如何使用 Requests 在线解码 pdf 中的文本?

python - 如何在灰度图像上应用渐变贴图

python - 如何测试 Python readline 完成?

python - Django NoReverseMatch

python - 如何使用 Flask-RESTful 在 Dropbox 的 REST API 中传递文件路径?

python - 如何同时修改numpy数组的N列?