Basj Basj - 3 months ago 21
Python Question

Put a 1D array into a 2D array

I have a 2D array

x
in which I want to copy the content of a 1D array
y
:

import numpy as np
x = np.array([[1, 2], [4, 5], [3, 3]], np.int32)
y = np.array([1, 2, 3, 4, 5, 6])

x[:,:] = y # i would like x to be [[1, 2], [3, 4], [5, 6]]



ValueError: could not broadcast input array from shape (6) into shape (3,2)


How to do this ?

Answer

You have to convert the y to an array with a shape like x:

>>> x = y.reshape(x.shape)
>>> x
array([[1, 2],
       [3, 4],
       [5, 6]])

But note that the y should be reshape with x's shape.

Comments