+1 vote
in Programming Languages by (60.0k points)

I am concatenating a 1D numpy array to a 2D numpy array, but the code gives the following error:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (2, 3) + inhomogeneous part.

How can I fix this error?

Here is the code:

>>> import numpy as np

>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]])

>>> b=np.array([10,11,12])

>>> np.concatenate([[a,b]])

1 Answer

+2 votes
by (75.9k points)
selected by
 
Best answer

You are getting the error because you are using the concatenate() function to concatenate a 1D array with a 2D array. To fix the error, you need to use the vstack() function.

Here is the solution:

>>> import numpy as np

>>> a=np.array([[1,2,3],[4,5,6],[7,8,9]])

>>> a

array([[1, 2, 3],

       [4, 5, 6],

       [7, 8, 9]])

>>> b=np.array([10,11,12])

>>> b

array([10, 11, 12])

>>> c=np.vstack([a,b])

>>> c

array([[ 1,  2,  3],

       [ 4,  5,  6],

       [ 7,  8,  9],

       [10, 11, 12]])


...