The shape
of a NumPy array tells you the dimensions of the array — basically, how many elements are in each axis (dimension). Understanding the shape is crucial for working with arrays efficiently.
The shape is a tuple of integers representing the size of the array along each dimension.
import numpy as np
arr1 = np.array([1, 2, 3, 4])
print(arr1.shape) # Output: (4,)
Here, (4,)
means the array is 1-dimensional with 4 elements.
For 2D or higher dimensional arrays, shape tells the size along each axis.
arr2 = np.array([[1, 2, 3],
[4, 5, 6]])
print(arr2.shape) # Output: (2, 3)
This means 2 rows and 3 columns.
You can change the shape of an array using reshape()
if the total number of elements remains the same.
arr = np.arange(12) # Creates array with elements 0 to 11
print(arr.shape) # (12,)
arr_reshaped = arr.reshape(3, 4)
print(arr_reshaped.shape) # (3, 4)
print(arr_reshaped)
# Output:
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
-1
in reshape to infer dimension automatically.When you put -1
in one dimension, NumPy calculates it automatically.
arr = np.arange(8)
reshaped = arr.reshape(2, -1) # -1 means "figure it out"
print(reshaped.shape) # Output: (2, 4)
print(reshaped)
# [[0 1 2 3]
# [4 5 6 7]]
arr.shape
returns the shape tuple.arr.reshape(new_shape)
changes the shape (returns a new array or view).Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!