pythonnumpy

Concatenate with broadcast


Consider the following arrays:

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

Is there a simple way to concatenate these two arrays in a way that the latter is broadcast, in order to obtain the following?

array([[0, 1, 2, 3],
       [1, 1, 2, 3]])

I've seen there is this closed issue with a related question. An alternative is proposed involving np.broadcast_arrays, however I cannot manage to adapt it to my example. Is there some way to do this, excluding the np.tile/np.concatenate solution?


Solution

  • You can do it in the following way

    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)