python - How to assign a 1D numpy array to 2D numpy array? -
consider 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: not broadcast input array shape (10) shape (10,1) x[:,0:1] = (x.reshape(-1, 1)) # works can explain why numpy has vectors of shape (n,) rather (n,1) ? best way casting 1d array 2d array?
why need this? because have code inserts result x 2d array x , size of x changes time time have x[:, idx1:idx2] = x works if x 2d not if x 1d.
do need able handle both 1d , 2d inputs same function? if know input going 1d, use
x[:, i] = x if know input going 2d, use
x[:, start:end] = x if don't know input dimensions, recommend switching between 1 line or other if, though there might indexing trick i'm not aware of handle both identically.
your x has shape (n,) rather shape (n, 1) (or (1, n)) because numpy isn't built matrix math. ndarrays n-dimensional; support efficient, consistent vectorized operations non-negative number of dimensions (including 0). while may make matrix operations bit less concise (especially in case of dot matrix multiplication), produces more applicable code when data naturally 1-dimensional or 3-, 4-, or n-dimensional.
Comments
Post a Comment