与广播连接

时间:2019-05-29 09:14:43

标签: python numpy

考虑以下数组:

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]])

我已经看到this个已关闭的问题,相关的问题。提出了一个涉及np.broadcast_arrays的替代方法,但是我无法使其适应我的示例。除了np.tile / np.concatenate解决方案之外,是否有其他方法可以做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式完成

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)

答案 1 :(得分:0)

以下是更通用的解决方案:

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)