7

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 vectors of shape (N,) rather than (N,1) ? What is the best way to do the casting from 1D array into 2D array?

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

3 Answers 3

4

Do you really need to be able to handle both 1D and 2D inputs with the same function? If you know the input is going to be 1D, use

X[:, i] = x

If you know the input is going to be 2D, use

X[:, start:end] = x

If you don't know the input dimensions, I recommend switching between one line or the other with an if, though there might be some indexing trick I'm not aware of that would handle both identically.

Your x has shape (N,) rather than shape (N, 1) (or (1, N)) because numpy isn't built for just matrix math. ndarrays are n-dimensional; they support efficient, consistent vectorized operations for any non-negative number of dimensions (including 0). While this may occasionally make matrix operations a bit less concise (especially in the case of dot for matrix multiplication), it produces more generally applicable code for when your data is naturally 1-dimensional or 3-, 4-, or n-dimensional.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Line 3 makes perfect sense for me and I would assign to the 2-D array this way.

Comments

0

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 
X.T[:1, :] = x
X[:, 2:3] = x[:, None]

1 Comment

Could you add some more commentary? It's not clear to me how you got here from the original code, and why this solves the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.