How to Use the NumPy flatten() Method in Python

Contents
In this article, you will learn how to use the numpy flatten() method in Python.
NumPy flatten() Method
The flatten() method in NumPy is used to collapse a multi-dimensional NumPy array into a one-dimensional array.
Here’s how you can use it in Python:
import numpy as np
# Create a multi-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Use the flatten method to collapse the array
flattened_arr = arr.flatten()
# Print the result
print(flattened_arr)
# Output
# [1 2 3 4 5 6]
Note that the flatten() method returns a flattened array as a copy. If you want to modify the original array in-place, you can use the ravel() method instead:
import numpy as np
# Create a multi-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Use the ravel method to collapse the array
arr.ravel()
# Print the result
print(arr)
# Output
# [1 2 3 4 5 6]
The flatten() method has several optional parameters that you can use to control the behavior of the method:
order
Specifies the memory layout of the flattened array. The default is ‘C’ (row-major), but you can use ‘F’ for column-major order.
import numpy as np
# Create a multi-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Use the flatten method to collapse the array with column-major order
flattened_arr = arr.flatten(order='F')
# Print the result
print(flattened_arr)
# Output
# [1 4 2 5 3 6]
copy
Specifies whether the flattened array should be a copy of the original data. The default is True, which means that the flattened array will be a copy of the original data. If you set copy to False, the flattened array will be a view of the original data and any changes made to the flattened array will be reflected in the original data.
import numpy as np
# Create a multi-dimensional array
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Use the flatten method to collapse the array without creating a copy
flattened_arr = arr.flatten(copy=False)
# Print the result
print(flattened_arr)
# Output
# [1 2 3 4 5 6]
Note that in this case, the flattened_arr is a view of the original data, so any changes made to the flattened_arr will also be reflected in the original data.