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

0 votes
1 view
in Python
edited

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.

0 votes
by (107k points)

# The correct and efficient way to flatten array in numpy in python, you can use the reshape method see the code below:-

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

To know more about this you can have a look at the following video tutorial:-

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer