How to assign 1D numpy array to 2D numpy array?

Consider the following simple example:

X = numpy.zeros([10, 4]) # 2D array x = numpy.arange(0,10) # 1D array X[:,0] = x # WORKS X[:,0:1] = x # returns ERROR: # ValueError: could not broadcast input array from shape (10) into shape (10,1) X[:,0:1] = (x.reshape(-1, 1)) # WORKS 

Can someone explain why numpy has form vectors (N,) and not (N, 1)? What is the best way to cast from a 1D array to a 2D array?

Why do I need it? Because I have code that inserts the result of x into the 2D array x , and the size of x changes from time to time, so I X[:, idx1:idx2] = x works if x also 2D, but not if x is 1D .

+7
python arrays numpy multidimensional-array
source share
3 answers

Do you really need to be able to handle both one-dimensional and two-dimensional inputs with the same function? If you know the input will be 1D, use

 X[:, i] = x 

If you know that the input will be 2D, use

 X[:, start:end] = x 

If you don't know the size of the input, I recommend switching between one line or the other with if , although there might be some kind of indexing trick that I don't know will handle both the same.

Your x has a form (N,) , not a form (N, 1) (or (1, N) ), because numpy is not built just for a mathematical matrix. ndarrays n-dimensional; they support efficient, consistent vectorized operations for any non-negative number of dimensions (including 0). Although this can sometimes lead to a smaller reduction in operations with matrices (especially in the case of dot for matrix multiplication), it creates more generally applicable code when your data is naturally one-dimensional or 3-, 4- or n-dimensional.

+4
source share

I think you have an answer already included in your question. Numpy allows arrays to be any dimension (while afaik Matlab prefers two dimensions where possible), so you need to be correct with that (and always distinguish between (n,) and (n, 1)). By giving one number as one of the indices (for example, 0 in the 3rd row), you reduce the dimension by one. By giving the range as one of the indices (for example, 0: 1 in the 4th row), you do not reduce the dimension.

Line 3 makes perfect sense for me, and I would assign to a 2-dimensional array this way.

0
source share

Here are two tricks that make the code a little shorter.

 X = numpy.zeros([10, 4]) # 2D array x = numpy.arange(0,10) # 1D array XT[:1, :] = x X[:, 2:3] = x[:, None] 
0
source share

All Articles