NUMPY Tutorial



NumPy ARRAY SHAPES


🔹 NumPy Array Shape

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.

✅ What is Shape?

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.

🎲 Multi-dimensional Arrays

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.

🧰 Reshaping Arrays

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]]

⚠️ Important Points

  • Total elements before and after reshape must be the same (e.g., 12 elements can reshape into (3,4) but not (5,3)).
  • Use -1 in reshape to infer dimension automatically.

🔀 Using -1 in Reshape

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]]

🔎 Quick Shape Checks and Usage

  • arr.shape returns the shape tuple.
  • arr.reshape(new_shape) changes the shape (returns a new array or view).
  • Shape is useful for array operations like matrix multiplication, broadcasting, and slicing.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review