P02.1 · Arrays, shapes and data types
P02.1 L1 · Core 4 lessons · about 100 min Live · in review
Part of P02 Scientific Python: NumPy, pandas and Plotting in the Programming and Data track.
Every dataset, image and set of model weights in machine learning is stored as a NumPy array: one block of numbers of a single type, with a shape that says how to read it as a grid. These four lessons build the array up from the Python list, read its shape and axes on the course’s weather table, show that reshaping only moves the row breaks while a transpose changes the reading order, and open up the data type, from how many bytes an entry takes to why 200 + 100 can come out as 44.
What you need first. Plain Python: lists, nesting and copies (P01.6), loops and functions (P01.3, P01.4), integer division and remainders (P01.2), and comprehensions (P01.10). No NumPy is assumed.
Lessons
From lists to arrays P02.1.1 25 min
A Python list holds references to separate objects; a NumPy array holds one block of numbers of a single type. Add and scale readings element by element with a loop, then with an array, and make arrays with np.array, zeros, ones, arange and linspace.
Shape, axes and dimensions P02.1.2 25 min
A 2-D array is a grid: the weather table temps has shape (4, 3), ndim 2 and size 12, with axis 0 down the days and axis 1 across the stations. Find a shape by hand, name one entry as temps[i, j], and add a third axis for colour images.
Reshaping: same values, new shape P02.1.3 25 min
Reshaping keeps an array’s values in their row-by-row reading order and moves only the row breaks. Derive the flat position k = i * n_cols + j, use reshape, ravel and unravel_index, join arrays with concatenate and stack, and see why reshape is not a transpose.
Data types: what one number can hold P02.1.4 25 min
Every entry of an array shares one dtype, so nbytes = size * itemsize. Work the edges by hand before NumPy shows them: uint8 wraps round so 200 + 100 gives 44, float64 keeps about 16 digits, NaN is a float, astype(int) cuts toward zero, and mixed types promote.
The interactive
P02.1-X1 · Shape shifter. Twelve numbered cells re-flow into the shapes (12,), (4, 3), (3, 4), (2, 6) and (2, 3, 2), each axis drawn as a labelled arrow. Tap a cell to read its index and its flat position, and toggle the transpose to see the reading order change where reshape kept it. It lives in Reshaping: same values, new shape.