Introduction to Python NumPy Array Reshaping
Python NumPy Array Reshaping
In NumPy, you can reshape an array to change its dimensions and organization of elements using the reshape()
function or the reshape method.
Reshaping allows you to rearrange the elements of an array while maintaining the same total number of elements.
Here's how you can reshape a NumPy array:
Using reshape()
function
The reshape()
function takes the array and the desired shape as arguments and returns a new array with the specified shape.
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
reshaped_arr = np.reshape(arr, (2, 3))
print(reshaped_arr)
Output:
[[1 2 3]
[4 5 6]]
In the example above:
- The original 1-dimensional array
arr
is reshaped into a 2-dimensional array with a shape of(2, 3)
.
Using reshape method
The reshape()
method can also be called directly on the array, which returns a new array with the specified shape.
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]]
Both approaches achieve the same result of reshaping the array.
The shape provided to reshape()
should be compatible with the total number of elements in the original array. For example, if the original array has 12 elements, valid reshapes include (2, 6), (3, 4), or (6, 2), but invalid reshapes include (3, 3) or (4, 4).