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.

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}")

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.

## 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}")

As you can see array got flattened as well. -1 parameter

## 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]

## Difference Between `flatten()` and `ravel()`

The `flatten()` and `ravel()` functions are both used to flatten an array in NumPy. However, there are some key differences between the two functions.

The `flatten()` function always creates a new array, even if the original array is already a 1D array. The `ravel()` function, on the other hand, only creates a new array if the original array is not a 1D array.

The `flatten()` function is more efficient than the `ravel()` function, because it does not need to check if the original array is a 1D array.

The flatten() and ravel() functions both create a 1D array from the original array. However, the flatten() function creates a new array, while the ravel() function only creates a view of the original array.