Mapping a Function Over an ArrayMapping a Function Over an Array

Mapping a function over a NumPy array means applying a given function to each element of the array, resulting in a new array with transformed values. This operation is essential for various data processing and analytics tasks.

Using loops for this purpose is cumbersome and inefficient most of the time, so we'll discuss other approaches. Here are three most common ones:

  • applying a function directly;
  • using the numpy.vectorize() function;
  • using universal functions.

Applying a Function Directly

The simplest way to map a certain function over an array is by applying it directly to an array. This approach can be used when a function performs a simple (e.g., mathematical) operation and returns something.

Let’s have a look at an example:

As you can see, we created a simple lambda function to square the element of the array.

Note

NumPy has a powerful feature called broadcasting, which allows element-wise operations between arrays of compatible shapes.

In this case, the scalar value 2 is broadcast to match the shape of the array. Broadcasting allows NumPy to efficiently perform operations on arrays without the need for explicit loops.

In fact, we could simply write result = array ** 2 without even creating a lambda function.

numpy.vectorize()

NumPy provides the vectorize() function, which makes it easy to apply a function to each element of an array.

Let’s have a look at an example of a case when you wouldn’t be able to apply the function directly:

Simply applying this function directly would return the length of the array, so we first vectorized it and only then applied it to our array to return an array where each element is the length of each word.

Universal Functions

NumPy also provides universal functions (ufuncs) that are highly optimized functions for element-wise operations. These functions are faster and more efficient than using loops or vectorization.

Here is an example with the numpy.square() universal function:

As you can see, universal functions are quite useful for applying a certain mathematical function on the array elements. You can explore more of these functions here.

Note

All of the mentioned approaches work the same way on the higher dimensional arrays performing element-wise operations.

Everything was clear?

Section 3. Chapter 6