Arrays and shapes
Step 1 of 18 in Foundations · Concept · Easy
A NumPy array is a grid of numbers with a shape like (rows, cols). Almost every AI bug starts as a shape mismatch, so learn to read and reshape them fluently.
The lesson
A NumPy array is one block of numbers plus a shape: a tuple that says how long each axis is. (3,) is three numbers in a line. (2, 3) is 2 rows of 3. (2, 3, 4) is 2 blocks, each with 3 rows of 4.
import numpy as np
a = np.arange(12) # shape (12,)
b = a.reshape(3, 4) # shape (3, 4): the same 12 numbers, laid out differently
b.T.shape # (4, 3): transpose reverses the axes
b[0].shape # (4,): an integer index removes that axis
b[0:1].shape # (1, 4): a slice keeps itReshaping never changes how many numbers there are, so the sizes must multiply to the same total. Write -1 for one axis and NumPy works it out: a.reshape(2, -1) gives (2, 6).
Common mistake. (3,), (3, 1) and (1, 3) are three different shapes. A (3,) array has a single axis; it is neither a row nor a column. Most shape bugs come from treating these as the same thing.
Check yourself
x has shape (2, 3, 4). What is x[1].shape?
- (2, 4)
- (3, 4)
- (1, 3, 4)
Show the answer
(3, 4). An integer index removes the axis it indexes. Axis 0 goes, leaving (3, 4). A slice, x[1:2], would have kept it as (1, 3, 4).
a has shape (6, 4). After a.reshape(3, -1), how long is the second axis?
Show the answer
8. There are 6 × 4 = 24 numbers. With 3 on the first axis, the second must be 24 / 3 = 8.
x has shape (5, 3). What is x.T[0:2].shape?
- (2, 3)
- (5, 2)
- (2, 5)
Show the answer
(2, 5). x.T has shape (3, 5). A slice of 2 along the first axis keeps both axes: (2, 5).
Build it
Shape drills
Create arrays of shape (3,), (3,1), (1,3), (2,3,4). Reshape, transpose and index slices of each; print .shape after every operation.
Done when: You can predict every printed shape before running the line.
Resources
- Wikipedia: NumPy Article
- NumPy: absolute beginners Article
- Kaggle Learn: Python Course
Earn this star
On the map, your answers are marked and you log what you built. Finish the step and its star lights.
Open this step on the map