Python | Flatten a 2D Numpy Array into 1D Array
Given a 2D NumPy array, the task is to convert it into a 1D array. Flattening helps when you want to convert matrix-style data into a single list-like structure for further processing. For Example:
Input: [[1, 2], [3, 4]]
Output: [1 2 3 4]
Let's explore different ways to flatten a 2D NumPy array into a 1D array.
Using np.ravel()
ravel() tries to return a view of the original array (not a copy). It reads values row-wise and presents them as a 1D array, making it the most efficient method.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
res = a.ravel()
print(res)
Output
[1 2 3 4 5 6]
Using np.ndarray.flatten()
flatten() creates a new copy of the data and converts the array into a row-major 1D array.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
res = a.flatten()
print(res)
Output
[1 2 3 4 5 6]
Using reshape(-1)
reshape(-1) converts any array into a 1D array. The -1 tells NumPy to automatically compute the required length.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
res = a.reshape(-1)
print(res)
Output
[1 2 3 4 5 6]
Explanation:
- a.reshape(-1) reshapes the structure into one dimension.
- -1 NumPy figures out the correct final size on its own.
Using np.concatenate()
concatenate() joins all inner arrays (rows) one after another, forming a single continuous 1D array.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
res = np.concatenate(a)
print(res)
Output
[1 2 3 4 5 6]
Explanation: np.concatenate(a) combines each row from a into one long array.