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.
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.
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]
Using lambda function to Map a Function Over N-D NumPy Array
Here we are using lambda function and mapping it with the a function over a multi dimension numpy array.
Python3
import numpy as np
data = np.array([[ 1 , 2 , 3 , 4 ], [ 5 , 6 , 7 , 8 ]])
print (data)
my_function = lambda x: x * 2 + 5
my_function(data)
|
Output:
[[1 2 3 4] [5 6 7 8]]
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.
Last Updated :
13 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...