Bird
0
0

You want to apply a custom function to each element of a large NumPy array efficiently. Which method is best?

hard📝 Application Q9 of 15
SciPy - Integration with Scientific Ecosystem
You want to apply a custom function to each element of a large NumPy array efficiently. Which method is best?
AUse a Python for loop to apply the function to each element
BUse np.vectorize to apply the function element-wise
CConvert array to list and use map() with the function
DUse np.dot to apply the function
Step-by-Step Solution
Solution:
  1. Step 1: Understand np.vectorize purpose

    np.vectorize wraps a Python function to apply element-wise over arrays efficiently.
  2. Step 2: Compare alternatives

    Python loops and map() are slower; np.dot is for matrix multiplication, not function application.
  3. Final Answer:

    Use np.vectorize to apply the function element-wise -> Option B
  4. Quick Check:

    np.vectorize applies functions element-wise efficiently [OK]
Quick Trick: np.vectorize wraps functions for array-wide application [OK]
Common Mistakes:
  • Using slow Python loops
  • Misusing np.dot for function application
  • Converting arrays to lists unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SciPy Quizzes