numpy 中的逐元素连接
Elementwise concatenation in numpy
我正在尝试连接 2 个数组元素。我有连接工作以产生正确的形状,但它没有被应用到元素明智。
所以我有这个数组
[0, 1]
[2, 3]
[4, 5]
我想将数组中的每个元素附加到每个元素。目标结果将是
[0, 1, 0, 1]
[0, 1, 2, 3]
[0, 1, 4, 5]
[2, 3, 0, 1]
[2, 3, 2, 3]
[2, 3, 4, 5]
[4, 5, 0, 1]
[4, 5, 2, 3]
[4, 5, 4, 5]
我想我可能需要更改轴,但我无法让广播正常工作。
如有任何帮助,我们将不胜感激。在 numpy 中有很多东西要学!
a = np.arange(6).reshape(3, 2))
b = np.concatenate((a, a), axis=1)
一种方法是堆叠使用 np.repeat
和 np.tile
-
创建的复制版本
In [52]: n = len(a)
In [53]: np.hstack((np.repeat(a,n,axis=0),np.tile(a,(n,1))))
Out[53]:
array([[0, 1, 0, 1],
[0, 1, 2, 3],
[0, 1, 4, 5],
[2, 3, 0, 1],
[2, 3, 2, 3],
[2, 3, 4, 5],
[4, 5, 0, 1],
[4, 5, 2, 3],
[4, 5, 4, 5]])
另一个是 broadcasted-assignment
,因为你提到了 broadcasting
-
def create_mesh(a):
m,n = a.shape
out = np.empty((m,m,2*n),dtype=a.dtype)
out[...,:n] = a[:,None]
out[...,n:] = a
return out.reshape(-1,2*n)
一个解决方案是建立在 senderle 的 cartesian_product
上,将其扩展到二维数组。以下是我通常这样做的方式:
# Your input array.
arr
# array([[0, 1],
# [2, 3],
# [4, 5]])
idxs = cartesian_product(*[np.arange(len(arr))] * 2)
arr[idxs].reshape(idxs.shape[0], -1)
# array([[0, 1, 0, 1],
# [0, 1, 2, 3],
# [0, 1, 4, 5],
# [2, 3, 0, 1],
# [2, 3, 2, 3],
# [2, 3, 4, 5],
# [4, 5, 0, 1],
# [4, 5, 2, 3],
# [4, 5, 4, 5]])
我正在尝试连接 2 个数组元素。我有连接工作以产生正确的形状,但它没有被应用到元素明智。
所以我有这个数组
[0, 1]
[2, 3]
[4, 5]
我想将数组中的每个元素附加到每个元素。目标结果将是
[0, 1, 0, 1]
[0, 1, 2, 3]
[0, 1, 4, 5]
[2, 3, 0, 1]
[2, 3, 2, 3]
[2, 3, 4, 5]
[4, 5, 0, 1]
[4, 5, 2, 3]
[4, 5, 4, 5]
我想我可能需要更改轴,但我无法让广播正常工作。
如有任何帮助,我们将不胜感激。在 numpy 中有很多东西要学!
a = np.arange(6).reshape(3, 2))
b = np.concatenate((a, a), axis=1)
一种方法是堆叠使用 np.repeat
和 np.tile
-
In [52]: n = len(a)
In [53]: np.hstack((np.repeat(a,n,axis=0),np.tile(a,(n,1))))
Out[53]:
array([[0, 1, 0, 1],
[0, 1, 2, 3],
[0, 1, 4, 5],
[2, 3, 0, 1],
[2, 3, 2, 3],
[2, 3, 4, 5],
[4, 5, 0, 1],
[4, 5, 2, 3],
[4, 5, 4, 5]])
另一个是 broadcasted-assignment
,因为你提到了 broadcasting
-
def create_mesh(a):
m,n = a.shape
out = np.empty((m,m,2*n),dtype=a.dtype)
out[...,:n] = a[:,None]
out[...,n:] = a
return out.reshape(-1,2*n)
一个解决方案是建立在 senderle 的 cartesian_product
上,将其扩展到二维数组。以下是我通常这样做的方式:
# Your input array.
arr
# array([[0, 1],
# [2, 3],
# [4, 5]])
idxs = cartesian_product(*[np.arange(len(arr))] * 2)
arr[idxs].reshape(idxs.shape[0], -1)
# array([[0, 1, 0, 1],
# [0, 1, 2, 3],
# [0, 1, 4, 5],
# [2, 3, 0, 1],
# [2, 3, 2, 3],
# [2, 3, 4, 5],
# [4, 5, 0, 1],
# [4, 5, 2, 3],
# [4, 5, 4, 5]])