与广播concatenate

问题描述 投票:0回答:4
考虑以下数组:

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)
    

python numpy
4个回答
8
投票

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)



2
投票
x

和大小

y
(X, c1)

0
投票
(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,
    


0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.