Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate with broadcast

Tags:

python

numpy

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?

like image 266
yatu Avatar asked May 29 '19 09:05

yatu


People also ask

How do you concatenate two arrays of different dimensions in Python?

arange(2) is given. To concatenate the array of two different dimensions. The np. column_stack((array1, array2)) is used.

How do I concatenate 3d NumPy arrays?

Python NumPy concatenate 3d arrays In this method, we can easily use np. concatenate() function. In this method, the axis value is 0 and 1 to join the column and row-wise elements.


1 Answers

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)
like image 112
Anubhav Natani Avatar answered Sep 19 '22 09:09

Anubhav Natani