Sometimes, we want to map function over numpy array with Python.
In this article, we’ll look at how to map function over numpy array with Python.
How to map function over numpy array with Python?
To map function over numpy array with Python, we can use the np.vectorize
method.
For instance, we write
import numpy as np
x = np.array([1, 2, 3, 4, 5])
squarer = lambda t: t ** 2
f = np.vectorize(squarer)
y = f(x)
to create the squarer
function that returns t
raised to the power of 2.
Then we call vectorize
with squarer
to return a function that we can use on a numpy array to call the function to map all items in the numpy array to the new values.
And then we call f
with x
to return the numpy array y
with the values in x
squared.
Conclusion
To map function over numpy array with Python, we can use the np.vectorize
method.