Explain np.vectorize and clarify whether it provides a performance speedup or is primarily for convenience.

Quick Overview

Asks what np.vectorize does when it wraps a scalar Python function and whether it makes NumPy code faster. Tests your understanding of where element-wise work runs, how true ufuncs differ, and the output dtype pitfall of vectorize.

Explain np.vectorize and clarify whether it provides a performance speedup or is primarily for convenience.

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

Explain `np.vectorize` and clarify whether it provides a performance speedup or is primarily for convenience. ```hint Follow one element Ask where the per-element work happens when you call the wrapped function on an array, and how you would time it against a plain list comprehension. ``` ### What a Strong Answer Covers - What `np.vectorize` does for a scalar function (broadcasting, output shape and type) - Where the per-element loop actually runs and what that means for speed - Faster alternatives when a native array expression exists - When using it is still reasonable ### Follow-up Questions - `np.vectorize(lambda x: x / 2 if x > 0 else 0)` applied to `np.array([-1, 3])` returns `array([0, 1])`. Why, and how do you fix it? - How would you get a real compiled speedup for a scalar function that has no NumPy equivalent? - How do `np.vectorize` and `np.frompyfunc` differ?

Overview: Asks what np.vectorize does when it wraps a scalar Python function and whether it makes NumPy code faster. Tests your understanding of where element-wise work runs, how true ufuncs differ, and the output dtype pitfall of vectorize.

Nov 24, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

Explain np.vectorize and clarify whether it provides a performance speedup or is primarily for convenience.

What a Strong Answer Covers Guidance

  • What np.vectorize does for a scalar function (broadcasting, output shape and type)
  • Where the per-element loop actually runs and what that means for speed
  • Faster alternatives when a native array expression exists
  • When using it is still reasonable

Follow-up Questions Guidance

  • np.vectorize(lambda x: x / 2 if x > 0 else 0) applied to np.array([-1, 3]) returns array([0, 1]) . Why, and how do you fix it?
  • How would you get a real compiled speedup for a scalar function that has no NumPy equivalent?
  • How do np.vectorize and np.frompyfunc differ?