In my new role at work, a good chunk of my programming is Python based and revolves around data analysis. I already knew Python, however I wanted a review libraries such as numpy and learn libraries such as pandas and matplotlib. This article discusses numpy, short for "Numerical Python". The goal of this article isn't to teach numpy to beginners, instead focusing on library aspects I found most interesting.

Numpy is a library used for data analysis and scientific computing. At its most basic level, numpy exposes an API for working with arrays of one or more dimensions. Numpy is often used in conjunction with higher-level libraries such as pandas, which builds upon numpy arrays.

A single-dimension numpy array containing the numbers 1 through 3 is created with the following code:

Since Python already has native lists, the typical question to ask is what benefits numpy arrays provide. First, numpy arrays are fast. Numpy stores its arrays in a separate storage location from other Python objects and avoids certain overheads found in all Python objects^{1}. Its lower level C implementation helps facilitate extremely fast array manipulation and analysis.

In my opinion, numpy's API is superior to the native Python list implementation. Simple array operations are performed in a more concise manner, and advanced commands exist that are challenging to implement in the Python list API. One of the simple features that shows the power of numpy is vectorization.

Numpy arrays provide vectorization abilities. Vectorization in numpy is when operations are applied to entire arrays instead of individual items within a for loop^{2}. Instead of writing a for loop for numpy arrays in Python code, the underlying numpy API uses a for loop in its C implementation, which is much faster than native Python. As a simple vectorization example, let's take a numpy array and multiply each element by two.

The output above is what you would see when running the code in a Jupyter Notebook. The initial arange() function creates an array of length 10 from 0 to 9. Next, a vectorization operation is performed. Each item in the array is multiplied by two. An equivalent Python list operation would use a for loop.

Vectorization operations on numpy arrays don't mutate the original array, instead creating a new array instance. Therefore, my native Python implementation first makes a copy of the existing list before making changes.

The numpy vectorization I wrote applied a multiplication operator (*) with a scalar value (2) to an array. Vectorization operators can also apply an operator with an array to an equally sized array^{4}. For example, the following code multiplies the items in each array with each other.

Once again, this would be more difficult to write with native Python lists.

I made the implementation a bit shorter with a list comprehension, however it still isn't as elegant as the numpy solution.

Related to vectorization, broadcasting is when vectorization operators are performed on two arrays of different sizes. Technically my first example, arr * 2, is an example of broadcasting an array of length N to an array of length 1^{5}. Numpy has certain rules for how broadcasting works between two arrays^{6}. Two arrays are eligible for broadcasting if:

Broadcasting Rules

Equal Dimensions

The dimension values for both arrays are equal. For example, an array of dimension 2 x 3 and another array of dimension 2 x 3 are eligible for broadcasting. Likewise, an array of dimension 2 x 3 x 4 and another array of dimension 3 x 4 are eligible for broadcasting. However, an array of dimension 2 x 3 and another array of dimension 3 x 2 are not eligible for broadcasting.

Single Dimension Equal to One

The dimension value in one array is greater than one while the other is equal to one. For example, an array of dimension 2 x 3 and another array of dimension 2 x 1 are eligible for broadcasting. Likewise, an array of dimension 2 x 3 x 4 and another array of dimension 1 x 4 are eligible for broadcasting.

Here are broadcasting results from the five scenarios I mentioned in my comparison table above:

Creation of lists in Python is straightforward yet limited in options. More complex list creation can be accomplished with list comprehensions, as shown in the section on vectorization. Still, even list comprehensions aren't as powerful as the API numpy exposes for array creation.

A good example is a reshaped numpy array. In comparison to a Python list created with a list comprehension, the numpy reshape() method is more explicit in describing what it accomplishes.

Python lists already provide pretty nice slicing capabilities. Numpy takes slicing to another level. Numpy extends the indexing and slicing syntax in Python single-dimension lists for use in multi-dimensional arrays. The following examples demonstrate multi-dimensional indexing and slicing.

Numpy indexing and slicing operations can contain conditional logic. Here are some more advanced indexing and slicing operations on the same numpy array instance.

Reshaping numpy arrays is easy with a variety of functions for altering data arrangements. Some of the basic ones include reshape(shape), flatten(), and T (short for transpose).

While vectorization and built-in numpy functions are extremely helpful when transforming numpy arrays, sometimes they aren't flexible enough for our needs. In this case, custom functions can be created. For example, I created the following function which converts miles to kilometers:

This function can be applied to each item in an array.

Unfortunately, this custom function is very slow. The following test shows the time taken by the custom function versus vectorization.

The performance problem is that custom functions live in Python instead of C, with the latter being much faster. Luckily it is possible to write fast custom numpy functions using a library called numba. Numba uses LLVM to convert Python code to assembly code^{7}. The mile to kilometer function is easily rewritten with numba.

The numba function is extremely fast! In fact, numba functions are often faster than their numpy vectorization counterparts.

Numpy is an array object library that exposes an elegant API which is fun to use. I've used it often at work and will likely find usages for it in my personal Python code. If you want to see more numpy code samples, check out my data analytics repository on GitHub.