Computer >> Computer tutorials >  >> Programming >> Python

Flatten a 2d numpy array into 1d array in Python


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.

With flatten

The flatten function in numpy is a direct way to convert the 2d array in to a 1D array.

Example

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)

Output

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]

With ravel

There is another function called ravel which will do a similar thing of flattening the 2D array into 1D.

Example

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)

Output

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]