np.vectorize()
np.vectorize wraps an ordinary Python function so it can be called on whole arrays.
In this page:
Syntax
vectorized = np.vectorize(function_name)
result = vectorized(arr)
np.vectorize()
np.vectorize applies a scalar function to each element with broadcasting. It is a convenience, not a speed-up, since it still loops in Python under the hood. For real speed, use ufuncs or np.where.
Note:
Specify otypes to control the output dtype.
Example: np.vectorize()
import numpy as np
def grade(score):
return "A" if score >= 90 else "B" if score >= 80 else "C"
vgrade = np.vectorize(grade)
print(vgrade(np.array([95, 85, 70])))
# Output:
# ['A' 'B' 'C']
Related Topics
Common Mistakes
- Expecting np.vectorize to be fast
- Skipping otypes with empty inputs
- Using it where a ufunc exists
Chapter Summary
- vectorize adds array support to scalar functions
- It is convenient, not fast
- Prefer ufuncs or where
- otypes sets the output type
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: