Reshaping Arrays in NumPy
NumPy provides various functions to reshape arrays, allowing you to modify their structure without changing the data. The primary functions used for reshaping are:
- reshape()
- flatten()
- ravel()
1. reshape()
The reshape() function changes the shape of an array without altering its data. The new shape must have the same number of elements as the original.
import numpy as np arr = np.array([1, 2, 3, 4, 5, 6]) reshaped_arr = arr.reshape(2, 3) print(reshaped_arr)
Output:
[[1 2 3] [4 5 6]]
2. flatten()
The flatten() function returns a copy of the array in a one-dimensional format.
arr = np.array([[1, 2, 3], [4, 5, 6]]) flattened_arr = arr.flatten() print(flattened_arr)
Output:
[1 2 3 4 5 6]
3. ravel()
The ravel() function also returns a one-dimensional array, but it tries to return a view of the original array when possible, instead of a copy.
arr = np.array([[1, 2, 3], [4, 5, 6]]) raveled_arr = arr.ravel() print(raveled_arr)
Output:
[1 2 3 4 5 6]
Conclusion
Reshaping arrays in NumPy is useful when you need to modify array structures for computation. The reshape() function changes the shape while keeping the data intact, flatten() creates a copy of the array in one dimension, and ravel() produces a flattened view where possible.