Explain Codes LogoExplain Codes Logo

Numpy array dimensions

python
numpy
array
dimension
Alex KataevbyAlex Kataev·Mar 1, 2025
TLDR

To get the size of each dimension (axis) in a NumPy array, use the array's .shape attribute. It offers the dimensions as a tuple:

import numpy as np my_array = np.array([[1, 2, 3], [4, 5, 6]]) print(my_array.shape) # Output: (2, 3)

Here, (2, 3) means the array has 2 rows and 3 columns - just like a compact rectangular candy box!

Unwrapping the .shape gift

.shape explained

The .shape attribute provides a tuple of integers, each digit telling the size of the corresponding dimension (axis) in the NumPy array. This tuple's length is the rank of the array.

weird_array = np.array([[[1], [2], [3]], [[4], [5], [6]]]) print(weird_array.shape) # Output: (2, 3, 1)

Dimension indexing

To access dimensions individually, you can index the shape tuple:

print(my_array.shape[0]) # Number of sweet rows print(my_array.shape[1]) # Number of delicious columns

Checking dimensions with .ndim

Need the count of dimensions (axes) in the array? There's an attribute for that! .ndim:

print(weird_array.ndim) # Output: 3

Where shape matters

Shape in broadcasting

Understanding the shape is a must when you're about to perform operations like broadcasting. It ensures dimensions align correctly, preventing nasty surprises!

candy_1 = np.array([1, 2, 3]) candy_2 = np.array([[4], [5], [6]]) print((candy_1 + candy_2).shape) # Broadcasting sugars (3,) and (3,1)

Reshaping arrays for fun

Feeling like a potter shaping clay? .reshape method alters the dimensions and your array keeps data intact. Perfect for pre-shaping data for machine learning models.

reshaped_sweets = my_array.reshape((3, 2)) print(reshaped_sweets.shape) # Output: (3, 2)

Iterating over multidimensional arrays

With nested loops over arrays, knowing the size of each dimension can save you from the "notorious" IndexError and bring about efficient candy distribution.

for i in range(my_array.shape[0]): for j in range(my_array.shape[1]): print(f"{my_array[i, j]} candy, please!", end=' ') print()

Shape-shifting tricks with arrays

Flattening

You can unroll your array to 1D using the .flatten() or .ravel() methods. These methods are sweet when dealing with functions demanding one-dimensional inputs!

flat_candies = weird_array.flatten() print(flat_candies.shape) # Output: (6,)

Pumping up dimensions

Need more dimensions? Use np.newaxis or .reshape to add an axis. Mostly handy in deep learning convolution!

pumped_candies = candy_1[:, np.newaxis] print(pumped_candies.shape) # Output: (3, 1)

Slicing and indexing

Shape can be affected by array slicing and advanced indexing. Slicing keeps the dimension, while integer indexing reduces it:

sliced_candies = weird_array[:, :2, :] print(sliced_candies.shape) # Output: (2, 2, 1) indexed_candies = weird_array[0, :, :] print(indexed_candies.shape) # Output: (3, 1)