Alex Rivera | Logout

correct and efficient way to flatten array in numpy in python?

Asked 2012-01-29T22:29:38.193
40

I have:

a = array([[1,2,3],[4,5,6]])

and I'd like to flatten it, joining the two inner lists into one flat array entry. I can do:

array(list(flatten(a)))

but that seems inefficient due to the list cast (I want to end up with an array and not a generator.)

Also, how can this be generalized to an array like this:

b = array([[[1,2,3],[4,5,6]], [[10,11,12],[13,14,15]]])

where the result should be:

b = array([[1,2,3,4,5,6],
           [10,11,12,13,14,15]])

are there builtin/efficient numpy/scipy operators for this? thanks.

Edit
Report

1 Answer

23

You can use the reshape method.

>>> import numpy
>>> b = numpy.array([[[1,2,3],[4,5,6]], [[10,11,12],[13,14,15]]])
>>> b.reshape([2, 6])
array([[ 1,  2,  3,  4,  5,  6],
       [10, 11, 12, 13, 14, 15]])
answered 2012-01-29T22:32:08.507

Your Answer