A 2d numpy array is an array of arrays. In this article we will see how to flatten it to get the elements as one dimensional arrays.
The flatten function in numpy is a direct way to convert the 2d array in to a 1D array.
import numpy as np array2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]]) # printing initial arrays print("Given array:\n",array2D) # Using flatten() res = array2D.flatten() # Result print("Flattened array:\n ", res)
Running the above code gives us the following result −
Given array: [[31 12 43] [21 9 16] [ 0 9 0]] Flattened array: [31 12 43 21 9 16 0 9 0]
There is another function called ravel which will do a similar thing of flattening the 2D array into 1D.
import numpy as np array2D = np.array([[31, 12, 43], [21, 9, 16], [0, 9, 0]]) # printing initial arrays print("Given array:\n",array2D) # Using ravel res = array2D.ravel() # Result print("Flattened array:\n ", res)
Running the above code gives us the following result −
Given array: [[31 12 43] [21 9 16] [ 0 9 0]] Flattened array: [31 12 43 21 9 16 0 9 0]