Search code examples
pythonnumpymultidimensional-arrayarray-broadcasting

How do I convert (3,) numpy vector to (2,2,3) matrix?


I have a following numpy array with the shape (3,)

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

How can I convert this vector to the shape of (2,2,3) array, i.e.

np.array([[[2,3,4],[2,3,4]],[[2,3,4],[2,3,4]]])

Solution

  • np.resize will roll it that way:

    np.resize(a, (2,2,3))
    

    Or just multiply:

    np.ones((2,2,3), dtype=a.dtype) * a