In this article, we will discuss how to use the shape and reshape method on the array.
1. numpy.shape(a)
It returns the shape of an array. The element of the shape tuple gives the lengths of the corresponding array dimension
#code for numpyshape import numpy as np arr = np.array([[5,6,7,8], [5, 6, 7, 8], [5,6,7,8]]) #print output print(arr.shape) Output: (3, 4)
One more example demonstrating how it will output for different array inputs:
#code for empty and 0 values as input import numpy as np #inputes arr = np.array(0) arr1 = np.array([]) #Printing Output: print(arr.shape) print(arr1.shape)
1. ()
2. (0,)
To reshape a NumPy array, we use the reshape() function. The reshape() function takes two arguments: the first is the array to be reshaped, and the second is the new shape. For example, let’s say we have a 1-dimensional array with shape (5,). We can reshape it to a 2-dimensional array with
shape (2, 2) like this:
import numpy as np # Create a 1-dimensional array a = np.array([1, 2, 3, 4, 5]) print("Original array:", a) # Reshape the array b = a.reshape(2, 2) print("Reshaped array:", b)
Output:
Original array: [1 2 3 4 5] Reshaped array: [[1 2] [3 4]]
Note that the number of elements in the original and reshaped arrays must be the same. In this example, the original array has 5 elements, and the reshaped array has 2×2 = 4 elements.
Another way to reshape a NumPy array is by using the reshape() function with the -1 argument. The -1 argument tells NumPy to automatically calculate the other dimension based on the number of elements and the shape provided.
For example, let’s say we have a 1-dimensional array with shape (8,). We can reshape it to a 2-dimensional array with shape (2, -1) like this:
import numpy as np # Create a 1-dimensional array a = np.array([1, 2, 3, 4, 5, 6, 7, 8]) print("Original array:", a) # Reshape the array with -1 b = a.reshape(2, -1) print("Reshaped array:", b)
Output:
Original array: [1 2 3 4 5 6 7 8] Reshaped array: [[1 2 3 4] [5 6 7 8]]
In this example, we have reshaped the original array with 8 elements to a 2-dimensional array with 2 rows and 4 columns.
In summary, reshaping is a powerful feature of NumPy that allows us to change the shape of an array without changing its data. The reshape() function is a convenient tool to reshape arrays, and the -1 argument can be used to automatically calculate one of the dimensions based on the number of elements and the shape provided.
Thanks for the read. Leave a comment in case of a query.