+2 votes
in Programming Languages by (11.5k points)
edited by
How can I flatten a 2D array into a 1D array in Python? The elements of column-1 should come first, then the elements of column-2 and so on.

E.g.

[[1, 2, 3],

 [4, 5, 6],

 [7, 8, 9]]

to

[1, 4, 7, 2, 5, 8, 3, 6, 9]

1 Answer

0 votes
by (20k points)

You can use either ravel() or flatten() function with order 'F' to convert a 2D array to a 1D array in column-major order.

Here is an example.

>>> aa=np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> aa
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])
>>> np.ravel(aa.T)
array([1, 4, 7, 2, 5, 8, 3, 6, 9])

>>> np.ravel(aa, order='F')
array([1, 4, 7, 2, 5, 8, 3, 6, 9])

>>> aa.flatten(order='F')
array([1, 4, 7, 2, 5, 8, 3, 6, 9])

...