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

PythonServer Side ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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]
raja
Published on 04-Jun-2020 12:07:15
Advertisements