Home > Software engineering >  Apply numpy broadcast_to on each vector in an array
Apply numpy broadcast_to on each vector in an array

Time:08-30

I want to apply something like this:

a = np.array([1,2,3])
np.broadcast_to(a, (3,3))

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

On each vector in a multi-vector array:

a = np.array([[1,2,3], [4,5,6]])
np.broadcast_to(a, (2,3,3))

ValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (2,3)  and requested shape (2,3,3)

To get something like this:

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

       [[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]]])

CodePudding user response:

One way is to use list-comprehension and broadcast each of the inner array:

>>> np.array([np.broadcast_to(i, (3,3)) for i in a])

array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],
       [[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]]])

Or, you can just add an extra dimension to a then call broadcast_to over it:

>>> np.broadcast_to(a[:,None], (2,3,3))

array([[[1, 2, 3],
        [1, 2, 3],
        [1, 2, 3]],
       [[4, 5, 6],
        [4, 5, 6],
        [4, 5, 6]]])
  • Related