How to Map a Function Over NumPy Array?
In this article, we are going to see how to map a function over a NumPy array in Python.
Method 1: numpy.vectorize() method
The numpy.vectorize() function maps functions on data structures that contain a sequence of objects like NumPy arrays. The nested sequence of objects or NumPy arrays as inputs and returns a single NumPy array or a tuple of NumPy arrays.
Python3
import numpy as np arr = np.array([1, 2, 3, 4, 5]) def addTwo(i): return i+2 applyall = np.vectorize(addTwo)res = applyall(arr)print(res) |
Output:
[3 4 5 6 7]
Explanation: The function is passed to the vectorized method and again the array is passed to it and the function will return the array on which the array is applied.
Method 2: Using lambda function
The lambda is an anonymous function, it takes any number of arguments but evaluates one expression.
Python3
import numpy as np arr = np.array([1, 2, 3, 4, 5]) def applyall(i): return i + 2 res = applyall(arr)print(res) |
Output:
[3 4 5 6 7]
Method 3: Using an array as the parameter of a function to map over a NumPy array
We can map a function over a NumPy array just by passing the array to the function.
Python3
import numpy as np arr = np.array([1, 2, 3, 4, 5]) def applyall(a): return a+2 res = applyall(arr)print(res) |
Output:
[3 4 5 6 7]
Explanation: The array is passed to the applyall() method and it will map the function to the entire array and the resultant array is returned.


