Reshaping in NumPy refers to changing the shape (dimensions) of an array without changing its data. This means that the total number of elements in the array remains the same after reshaping.
The reshape() function in NumPy allows you to do this. It returns a new array with the specified shape while maintaining the original data. Here's how it works:
import numpy as np
# Create a 1D array
arr = np.array([1, 2, 3, 4, 5, 6])
# Reshape the array into a 2D array with 3 rows and 2 columns
reshaped_arr = arr.reshape(3, 2)
print("Original array:")
print(arr)
print("Reshaped array:")
print(reshaped_arr)
Original array:
[1 2 3 4 5 6]
Reshaped array:
[[1 2]
[3 4]
[5 6]]
In this example, we start with a 1-dimensional array arr with 6 elements. We then use reshape(3, 2) to transform it into a 2-dimensional array with 3 rows and 2 columns. The resulting array reshaped_arr has the same data as arr, but it's arranged in a different shape.