Numpy array dimensions
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:
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.
Dimension indexing
To access dimensions individually, you can index the shape tuple:
Checking dimensions with .ndim
Need the count of dimensions (axes) in the array? There's an attribute for that! .ndim
:
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!
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.
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.
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!
Pumping up dimensions
Need more dimensions? Use np.newaxis
or .reshape
to add an axis. Mostly handy in deep learning convolution!
Slicing and indexing
Shape can be affected by array slicing and advanced indexing. Slicing keeps the dimension, while integer indexing reduces it:
Was this article helpful?