Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)
edited by

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.

1 Answer

0 votes
by (106k 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:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Aug 5, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer

Browse Categories

...