# Fix Python – From ND to 1D arrays

## Question

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)))
``````

but this requires me to know how many dimensions the original array has (and concatenate ’s when working with higher dimensions)

Is there a dimensions-independent way of getting a column/row vector from an arbitrary ndarray?

Now we will see solution for issue: From ND to 1D arrays

Use np.ravel (for a 1D view) or np.ndarray.flatten (for a 1D copy) or np.ndarray.flat (for an 1D iterator):

``````In : a = np.array([[1,2,3], [4,5,6]])

In : b = a.ravel()

In : b
Out: array([1, 2, 3, 4, 5, 6])
``````

Note that `ravel()` returns a `view` of `a` when possible. So modifying `b` also modifies `a`. `ravel()` returns a `view` when the 1D elements are contiguous in memory, but would return a `copy` if, for example, `a` were 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

``````In : c = a.flatten()
``````

If you just want an iterator, use `np.ndarray.flat`:

``````In : d = a.flat

In : d
Out: <numpy.flatiter object at 0x8ec2068>

In : list(d)
Out: [1, 2, 3, 4, 5, 6]
``````

This question is answered By – unutbu