What does the reshape() method do in NumPy?
a) Changes the shape of an array without changing its data
b) Reverses the elements of an array
c) Flattens a multidimensional array into a 1D array
d) Sorts the elements of an array
Answer:
a) Changes the shape of an array without changing its data
Explanation:
The reshape()
method in NumPy is used to change the shape of an array without altering its data. This method returns a new view of the original array with the specified shape.
import numpy as np
# Creating a 1D array
arr = np.arange(1, 10)
# Reshaping the array into a 3x3 matrix
reshaped_arr = arr.reshape((3, 3))
print(reshaped_arr)
In this example, a 1D array with values from 1 to 9 is reshaped into a 3×3 matrix using the reshape()
method.
Reshaping arrays is commonly used in data processing and machine learning to prepare data for specific algorithms or to match the dimensions required by mathematical operations.