NumPy
22 steps in 8 sets of Python.
NumPy is the layer nearly every scientific Python library is standing on, and the array is the only idea in it. This tour builds one, reshapes it, indexes it every way NumPy allows, and does arithmetic across it without a loop in sight.
The parts worth slowing down for are broadcasting, which is either elegant or baffling depending on the day, and the difference between a view and a copy, which is where the surprising bugs live. Dtypes, random generation and saving arrays round it out.
Arrays
- Creating arraysThe array constructors and shape basics of NumPy.
- Array indexingSlicing, fancy indexing, and boolean masks.
Math & shapes
- BroadcastingCombining arrays of different shapes without loops.
- Aggregation over axesReducing arrays with mean, sum, and friends per axis.
- Descriptive statisticsSummarizing a sample with NumPy's stats functions.
- Linear algebraMatrix products and the linalg toolkit.
Selection & random
- Conditional selection & sortingPicking, clipping, and ordering array values without loops.
- Random numbersThe modern Generator API for reproducible randomness.
Types & shapes
- Array dtypesOne dtype for the whole array is what makes numpy fast and strict.
- ReshapingSame buffer, different shape — as long as the sizes agree.
- Stacking and splittingJoining arrays along a new or existing axis, and cutting them back up.
- Broadcasting, preciselyShapes align from the right; a dimension of one stretches.
Indexing
- Boolean masksA boolean array selects, counts and assigns in one expression.
- Fancy indexingIndexing with arrays of positions, which copies rather than views.
- The axis argumentaxis=0 walks down the rows, axis=1 across the columns.
Maths & memory
- Universal functionsElement-wise maths that loops in C, not in Python.
- Views and copiesSlicing gives a view; forgetting that is how numpy surprises people.
- Solving linear systemssolve is the right answer; inverting the matrix is not.
- Why vectorizeThe same sum, three ways, and the reason numpy exists.
Randomness & storage
- The Generator APInp.random.default_rng is the modern, seedable source of randomness.
- Saving arraysnpy for one array, npz for several, savetxt when a human must read it.
Encore
- np_kmeans.pyCluster 2-D points with Lloyd's k-means in NumPy.