-1

I got a numpy array X which have shape (2 , 2 , 3) like this:

X = [[[1 , 2 , 3 ] 
       [4 , 5 , 6]] , 
     
      [[7 , 8 , 9 ] 
       [10, 11, 12 ]],

I want to flatten all subarrays and turn X to the shape of (2 , 6) which is represented like this:

X = [[ 1 , 2 , 3 , 4, 5 , 6 ] ,
     [ 7 , 8 , 9 , 10, 11 , 12 ] ]

But when I used X.flatten(), it just turned out to be like this:

X = [ 1 , 2, 3, 4 , 5, ... , 12]

Is there any function to help me transform the array like what I mean.

Guy
  • 46,488
  • 10
  • 44
  • 88
Miku
  • 79
  • 1
  • 7

4 Answers4

3

Just reshape....

import numpy as np

arr = np.array([[[1 , 2 , 3 ],
       [4 , 5 , 6]],
       [[7 , 8 , 9 ],
       [10, 11, 12 ]]])


arr.reshape(2, 6)

result:

array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12]])
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
2

Iterate over the array and flatten the sublists

arr = np.array([x.flatten() for x in X])

Or for numpy solution you can also use np.hstack()

arr = np.hstack(X)

Output

print(arr)
#[[ 1  2  3  4  5  6]
# [ 7  8  9 10 11 12]]
Guy
  • 46,488
  • 10
  • 44
  • 88
  • Yes I know it, but I'm asking for a module which can perform it immediately without having to iterate over all the subarrays please. – Miku Jul 28 '21 at 09:25
1

Loop through the array and flatten the subcomponents:

x = np.array([[[1,2],[3,4]], [[5,6],[7,8]]])
y = np.array([i.flatten() for i in x])
print(x)
print(y)

[[[1 2]
  [3 4]]

 [[5 6]
  [7 8]]]

[[1 2 3 4]
 [5 6 7 8]]
Jkind9
  • 742
  • 7
  • 24
1

If its an numpy array you can use reshape

x.reshape(2,6)

Input:

x = np.array([[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]]
x.reshape(2,6)

Output:

array([[ 1,  2,  3,  4,  5,  6],
   [ 7,  8,  9, 10, 11, 12]])
Eumel
  • 1,298
  • 1
  • 9
  • 19