Introducing NumPy, Part 4: Doing Math with Arrays

Quick Success Data Science

Plus reading and writing array data!

11 min read

3 hours ago

An array doing math as imagined by DALL-E3

Welcome to the fourth and final edition of the beginner series, Introducing NumPy! In the previous articles, we reviewed NumPy’s workhorse arrays: what they are and how to create them (Part 1); how to index and slice them (Part 2); and how to manipulate them (Part 3). Now it’s time to apply them to their main purpose: mathematical operations.

NumPy uses two internal implementations to perform math on arrays efficiently: vectorization and broadcasting. Vectorization supports operations between equal-sized arrays, and broadcasting extends this behavior to arrays with different shapes.

Vectorization

One of the most powerful features of ndarrays, vectorization lets you perform batch operations on data without the need for explicit for loops. This means you can apply an operation on an entire array at once without selecting each element from it.

Arithmetic operations are applied elementwise for equal-sized arrays, as shown in the following figure:

Because looping takes place behind the scenes with code implemented in C, vectorization leads to faster processing. Let’s look at an example in which we…