How to Map a Function Over NumPy Array?
Mapping a function over a NumPy array means applying a specific operation to each element individually. This lets you transform all elements of the array efficiently without writing explicit loops. For example, if you want to add 2 to every element in an array [1, 2, 3, 4, 5], the result will be [3, 4, 5, 6, 7] after applying the addition function to each element.
Using vectorized operation
This uses NumPy's broadcasting feature, where scalar 2 is automatically applied to each element of the array. It uses highly optimized low-level C loops internally.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
res = arr + 2
print(res)
Output
[3 4 5 6 7]
Explanation: operation arr + 2 uses NumPy's vectorized broadcasting to efficiently add 2 to each element without explicit loops.
Using np.add()
np.add() is a universal function ufunc provided by NumPy. It performs element-wise addition and is equivalent to arr + 2, but more explicit.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
res = np.add(arr, 2)
print(res)
Explanation: np.add(arr, 2) function performs element-wise addition by adding 2 to each element of the array.
Using lambda function
You can define an anonymous function using lambda and apply it to the entire NumPy array. NumPy allows broadcasting of such operations.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
res = (lambda x: x + 2)(arr)
print(res)
Output
[3 4 5 6 7]
Explanation: Lambda function (lambda x: x + 2) is immediately called with arr as the argument. This function adds 2 to each element of the array using NumPy’s broadcasting.
Using numpy.vectorize()
np.vectorize() takes a regular Python function and returns a vectorized version of it. It applies the function element-by-element over a NumPy array.
import numpy as np
a = np.array([1, 2, 3, 4, 5])
f = np.vectorize(lambda x: x + 2)
res = f(a)
print(res)
Output
[3 4 5 6 7]
Explanation: np.vectorize() which takes a Python lambda function that adds 2 to its input. When we call f(a), this vectorized function applies the lambda element-wise to each item in the array.