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)
PythonOutput:
Original 2D Array:
[[1, 2, 3]
[4, 5, 6]]
Flattened Array:
[1, 2, 3, 4, 5, 6]
PythonExplanation:
arr_2d.flatten()
converts the 2D arrayarr_2d
into a 1D array,flattened_arr
, by laying out the elements row by row.