How to Flatten an Array in NumPy

NumPy is a Python library for scientific computing. It provides a number of functions for working with arrays, including the ability to flatten an array.

Let’s check how to flatten an array in Numpy Python library.

Numpy flatten array

You can flatten your multidimensional array with NumPy. There are even two ways to do that.

How to flatten an array using Numpy flatten function?

You can flatten your Numpy array with flatten function. See below example.

import numpy as np

my_array = np.array([10, 20, 30, 40, 50, 60]).reshape(3, -1)
print("My Array: \n", my_array)

flatten_array = my_array.flatten()
print(f"Flatten Array: \n{flatten_array}")

Numpy flat array

The NumPy flatten method flattens the array. The flatten function just change multi dimension array into 1d array. In this example I showed how to change 2d array into 1d array.

See also  How to Generate a 3D Meshgrid Array in Numpy

How to flatten an array using Numpy reshape function?

The other possibility is to use a trick by reshaping the matrix to 1 row. Just use reshape(1, -1) to make Numpy to flatten your array.

import numpy as np

my_array = np.array([10, 20, 30, 40, 50, 60]).reshape(1, -1)
print("My Array: \n", my_array)

reshaped_array = my_array.reshape(1, -1)
print(f"Reshaped Array: \n{reshaped_array}")

Numpy reshape one row flatten array

As you can see array got flattened as well.

See also  How to you find the cumulative sum in Python?

How to flatten an array using Numpy ravel function?

You can use ravel method to flatten the array.

import numpy as np

my_array = np.array([10, 20, 30, 40, 50, 60]).reshape(3, -1)
print("My Array: \n", my_array)

flatten_array = my_array.ravel()
print(f"Flatten Array: \n{flatten_array}")

The output is the same:

Flatten Array: 
[10 20 30 40 50 60]