a = np.array([0,1])[:,None]
b = np.array([1,2,3])
print(a)
array([[0],
[1]])
print(b)
b = np.array([1,2,3])
有一种简单的方法来以播放后者的方式加入这两个阵列,以获取以下内容?
array([[0, 1, 2, 3],
[1, 1, 2, 3]])
np.broadcast_arrays
的替代方案,但是我无法将其适应我的示例。有什么方法可以做到这一点,不包括np.tile
/np.concatenate
解决方案?
您可以以以下方式做到这一点
import numpy as np
a = np.array([0,1])[:,None]
b = np.array([1,2,3])
b_new = np.broadcast_to(b,(a.shape[0],b.shape[0]))
c = np.concatenate((a,b_new),axis=1)
print(c)
def concatenate_broadcast(arrays, axis=-1):
def broadcast(x, shape):
shape = [*shape] # weak copy
shape[axis] = x.shape[axis]
return np.broadcast_to(x, shape)
shapes = [list(a.shape) for a in arrays]
for s in shapes:
s[axis] = 1
broadcast_shape = np.broadcast(*[
np.broadcast_to(0, s)
for s in shapes
]).shape
arrays = [broadcast(a, broadcast_shape) for a in arrays]
return np.concatenate(arrays, axis=axis)
x
和大小
y
和
(X, c1)
(Y, c2)
的行的所有串联,而行的行是
(X * Y, c1 + c2)
的。
像原始海报一样,我很失望地发现x
不会为我进行广播。 我想使用上面的解决方案,除了y
和concatenate()
可能很大,该解决方案将使用大型临时数组。
我终于提出了以下内容:
X
I创建一个大小的结果阵列,我在
Y
和 result = np.empty((x.shape[0], y.shape[0], x.shape[1] + y.shape[1]), dtype=x.dtype)
result[...,:x.shape[0]] = x[:,None,:]
result[...,x.shape[0]:] = y[None,:,:]
result = result.reshape((-1, x.shape[1] + y.shape[1]))
的内容中广播,然后将结果重塑为正确的大小。
(X, Y, c1 + c2)
通常解决这个问题。 x
之后,
y
gufunky.concatenate
正确处理边缘盒,例如连接阵列和串联空数组。在此答案时,它的工作原理如下。
pip install gufunky
https://github.com/johnadawson/gufunky/blob/master/src/gufunky.py,