Array Shapes, Axes, and Broadcasts
To understand how NumPy arrays behave in operations, we need to learn about shapes, axes, and broadcasting.
Shape
Every array has a .shape
, which tells you how many elements it has in each dimension.
For example, an array with 2 rows and 3 columns has a shape of (2, 3)
.
Axes
An axis is a direction you can move along in an array.
axis=0
→ down the rows (vertical)axis=1
→ across the columns (horizontal)
You’ll use axes when performing operations like sum()
, mean()
, and more.
Broadcasting
Broadcasting is how NumPy handles arrays of different shapes during arithmetic.
It “stretches” one array so the shapes line up.
This only works when the dimensions are compatible — we’ll look at examples in the slide deck.