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