← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 4 of 7

np.vectorize()

np.vectorize wraps an ordinary Python function so it can be called on whole arrays.

In this page:

  1. np.vectorize()
Syntax
python
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()

python
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
  1. Expecting np.vectorize to be fast
  2. Skipping otypes with empty inputs
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.