How to Map a Function Over a NumPy Array (With Examples)


You can use the following basic syntax to map a function over a NumPy array:

#define function
my_function = lambda x: x*5

#map function to every element in NumPy array
my_function(my_array)

The following examples show how to use this syntax in practice.

Example 1: Map Function Over 1-Dimensional NumPy Array

The following code shows how to map a function to a NumPy array that multiplies each value by 2 and then adds 5:

import numpy as np

#create NumPy array
data = np.array([1, 3, 4, 4, 7, 8, 13, 15])

#define function
my_function = lambda x: x*2+5

#apply function to NumPy array
my_function(data)

array([ 7, 11, 13, 13, 19, 21, 31, 35])

Here is how each value in the new array was calculated:

  • First value: 1*2+5 = 7
  • Second value: 3*2+5 = 11
  • Third value: 4*2+5 = 13

And so on.

Example 2: Map Function Over Multi-Dimensional NumPy Array

The following code shows how to map a function to a multi-dimensional NumPy array that multiplies each value by 2 and then adds 5:

import numpy as np

#create NumPy array
data = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

#view NumPy array
print(data)

[[1 2 3 4]
 [5 6 7 8]]

#define function
my_function = lambda x: x*2+5

#apply function to NumPy array
my_function(data)

array([[ 7,  9, 11, 13],
       [15, 17, 19, 21]])

Notice that this syntax worked with a multi-dimensional array just as well as it worked with a one-dimensional array.

Additional Resources

The following tutorials explain how to perform other common operations in NumPy:

How to Add a Column to a NumPy Array
How to Convert NumPy Array to List in Python
How to Export a NumPy Array to a CSV File

2 Replies to “How to Map a Function Over a NumPy Array (With Examples)”

  1. This isn’t mapping a function over the array. This is relying on the overloading of operators. `my_function` is called exactly once.

  2. This example is not correct. It implies that a lambda function will be applied to each element this way. What is actually happening is that the lambda function is being applied to the array, and the MATH operation automatically applies to each element.

    To understand the difference, create a lambda function that does not depend on ‘x’. For example: “lambda x: 0” When applying this to the array the result is just zero.

    Alternatively, if you apply the math operation without the lambda, it still works. Example: “my_array * 5”

    You can apply a function to each element by vectorizing the lambda. Example: “my_function = np.vectorize( lambda x: x*5 )”

Leave a Reply

Your email address will not be published. Required fields are marked *