这感觉像是应该已经有问题的东西,但我找不到。
在 numpy 中,假设我有两个数组 A
和 B
,我怎样才能确保它们相互“正交”广播,而不管要么数组?例如我可以这样做:
import numpy as np
A1 = np.zeros((2,2))
A2 = np.zeros((2,2,2))
B = np.ones((2,2))
C1 = A1 + B[...,np.newaxis,np.newaxis]
C2 = A2 + B[...,np.newaxis,np.newaxis,np.newaxis]
print(C1.shape)
print(C2.shape)
给出
(2, 2, 2, 2)
(2, 2, 2, 2, 2)
作为输出。但为了做到这一点,我必须知道至少一个数组的维数。有没有办法在不知道他们中的任何一个的情况下做到这一点?希望这是有道理的。
最佳答案
reshape B
以包含与 A
中的 dims 一样多的尾随单例维度 -
A + B.reshape(B.shape + tuple([1]*A.ndim)) # where A is generic ndarray
一些 NumPy ufuncs
有 outer
方法来处理所有这些工作。所以,对于添加,我们可以简单地使用 -
np.add.outer(B,A)
关于python - Numpy "orthogonal"广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49404966/