Flattening the Numpy arrays
Flattening an array means converting an array to a 1D array. We can use reshape(-1) to do this.
Example 1
Convert a 3D array into a 1D array
Python3
import numpy as np a = np.array([[ 'G' , 'F' , 'G' ], [ 'G' , 'F' , 'G' ], [ 'G' , 'F' , 'G' ]]) na = a.reshape( - 1 ) print (na) |
Output:
[‘G’ ‘F’ ‘G’ ‘G’ ‘F’ ‘G’ ‘G’ ‘F’ ‘G’]
Example 2
Convert the 2D array into a 1D array:
Python3
import numpy as np arr = np.array([[ 1 , 2 , 3 ], [ 4 , 5 , 6 ]]) newarr = arr.reshape( - 1 ) print (newarr) |
Output:
[1 2 3 4 5 6]