Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flattening an array only one layer?

Is there any built-in numpy function that would get:

a=np.asarray([[[1,2],[3,4]],[[1,2],[3,4]]])

And would return:

b=[[1,2],[3,4],[1,2],[3,4]]

? Something like like one layer flattening.

P.S. I am looking for a vectorized option otherwise this dumb code is available:

flat1D(a):
   b=np.array([])
   for item in a:
      b=np.append(b,item)
   return b
like image 361
Cupitor Avatar asked Feb 15 '23 21:02

Cupitor


1 Answers

You can simply reshape the array.

>>> a.reshape(-1,a.shape[-1])
array([[1, 2],
       [3, 4],
       [1, 2],
       [3, 4]])

The shown code returns a 1D array, to do this:

>>> a.ravel()
array([1, 2, 3, 4, 1, 2, 3, 4])

Or, if you are sure you want to copy the array:

>>> a.flatten()
array([1, 2, 3, 4, 1, 2, 3, 4])

The difference between ravel and flatten primarily comes from the fact that flatten will always return a copy and ravel will return a view if possible and a copy if not.

like image 80
Daniel Avatar answered Feb 27 '23 18:02

Daniel