Say I have an array a:
a = np.array([[1,2,3], [4,5,6]])
array([[1, 2, 3],
[4, 5, 6]])
I would like to convert it to a 1D array (i.e. a column vector):
b = np.reshape(a, (1,np.product(a.shape)))
but this returns
array([[1, 2, 3, 4, 5, 6]])
which is not the same as:
array([1, 2, 3, 4, 5, 6])
I can take the first element of this array to manually convert it to a 1D array:
b = np.reshape(a, (1,np.product(a.shape)))[0]
but this requires me to know how many dimensions the original array has (and concatenate [0]’s when working with higher dimensions)
Is there a dimensions-independent way of getting a column/row vector from an arbitrary ndarray?
Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):
Note that
ravel()returns aviewofawhen possible. So modifyingbalso modifiesa.ravel()returns aviewwhen the 1D elements are contiguous in memory, but would return acopyif, for example,awere made from slicing another array using a non-unit step size (e.g.a = x[::2]).If you want a copy rather than a view, use
If you just want an iterator, use
np.ndarray.flat: