Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

3 Answers 3

up vote 7 down vote accepted

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]])
share|improve this answer
    
I think it should be a.reshape([2,6]), thanks! –  user248237dfsf Jan 29 '12 at 22:35
    
@user248237: uh, sorry, I misread your question, still it's that method you have to use. Fixed now. :) –  Matteo Italia Jan 29 '12 at 22:36
3  
reshape() is a good method. –  Honghe.Wu Jul 10 '13 at 6:19
2  
And if you're lazy like me you can do b.reshape([2, -1]) –  usual me Jul 6 '14 at 10:40

How about:

>>> import numpy as np
>>> a=np.arange(1,7).reshape((2,3))
>>> a
array([[1, 2, 3],
       [4, 5, 6]])
>>> a.flatten()
array([1, 2, 3, 4, 5, 6])

and

>>> import numpy as np
>>> b=np.arange(1,13).reshape((2,2,3))
>>> b
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
>>> b.reshape((2,6))
array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12]])
share|improve this answer
    
+1 for flatten() -- it can also do Fortran/column-major flattening. reshape(-1) will also flatten. –  Dave X Oct 29 '13 at 19:50

You might need to check out numpy.flatten and numpy.ravel, both return a 1-d array from an n-d array.

Furthermore, if you're not going to modify the returned 1-d array, I suggest you use numpy.ravel, since it doesn't make a copy of the array, but just return a view of the array, which is much faster than numpy.flatten.

>>>a = np.arange(10000).reshape((100,100))

>>>%timeit a.flatten()
100000 loops, best of 3: 4.02 µs per loop

>>>%timeit a.ravel()
1000000 loops, best of 3: 412 ns per loop

Also check out this post.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.