1. Home
  2. Docs
  3. numpy
  4. Flattening Arrays

Flattening Arrays

Flattening is the process of converting a multi-dimensional array into a one-dimensional array.

Code Example:

import numpy as np

# Creating a 2D array
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Flattening the 2D array
flattened_arr = arr_2d.flatten()

print("Original 2D Array:\n", arr_2d)
print("\nFlattened Array:\n", flattened_arr)
Python

Output:

Original 2D Array:
 [[1, 2, 3]
 [4, 5, 6]]

Flattened Array:
 [1, 2, 3, 4, 5, 6]
Python

Explanation:

  • arr_2d.flatten() converts the 2D array arr_2d into a 1D array, flattened_arr, by laying out the elements row by row.

How can we help?