Let’s check how to flatten an array in Numpy Python library.
You can flat 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}")
Array got flatten by Numpy flatten method. 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]