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

Mapping a function over a NumPy array is a powerful way to quickly apply a specific function to each element of the array. This can be done using the map_function() method, which takes two arguments: the function to be applied and the NumPy array. For example, if you have an array of numbers and wish to square each element, you can use the map_function() method to easily apply the square function to each element of the array. The result will be a new array with the function applied to each element.


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.

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

x