Array Reshaping and Flattening
NumPy makes it easy to reshape arrays — changing the number of rows and columns without changing the data.
You can also flatten a multi-dimensional array into a 1D array.
Reshaping
Use .reshape(rows, columns)
to change the array’s shape.
The total number of elements must stay the same.
Reshape Example
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped = arr.reshape(2, 3)
print(reshaped)
# [[1 2 3]
# [4 5 6]]
Flattening
Use .flatten()
to turn any multi-dimensional array into a 1D array.
Flatten Example
matrix = np.array([[1, 2, 3], [4, 5, 6]])
flat = matrix.flatten()
print(flat) # [1 2 3 4 5 6]
Summary
- Use
.reshape()
to change an array’s shape (without changing its data) - Use
.flatten()
to convert any array to 1D
What’s Next
You’ll now practice reshaping and flattening arrays using code in Jupyter.