Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a 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 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.

like image 595
Hanan Shteingart Avatar asked Aug 26 '13 07:08

Hanan Shteingart


1 Answers

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.

like image 130
user2357112 supports Monica Avatar answered Oct 04 '22 21:10

user2357112 supports Monica