0
0
NumPydata~5 mins

np.vectorize() for custom functions in NumPy - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does np.vectorize() do in NumPy?

np.vectorize() turns a regular Python function into one that can be applied element-wise to arrays, like a loop but simpler to write.

Click to reveal answer
beginner
How does np.vectorize() help with custom functions?

It lets you apply your own function to each element of an array without writing explicit loops.

Click to reveal answer
intermediate
What is a limitation of np.vectorize() compared to true vectorized NumPy functions?

np.vectorize() is basically a loop under the hood, so it is not faster than a Python loop. It just makes code cleaner.

Click to reveal answer
beginner
Example: How to use np.vectorize() to square each element in an array using a custom function?
<pre>import numpy as np

def square(x):
    return x * x

vec_square = np.vectorize(square)
arr = np.array([1, 2, 3])
result = vec_square(arr)
print(result)  # Output: [1 4 9]</pre>
Click to reveal answer
intermediate
Can np.vectorize() handle functions with multiple inputs?

Yes, you can pass multiple arrays as arguments, and np.vectorize() will apply the function element-wise across all inputs.

Click to reveal answer
What is the main purpose of np.vectorize()?
ATo apply a function element-wise to arrays
BTo speed up NumPy operations
CTo create new NumPy arrays
DTo sort arrays
Does np.vectorize() improve performance compared to a Python loop?
AYes, it is much faster
BOnly for large arrays
CNo, it is similar in speed
DIt depends on the array size
Which of these is a correct way to create a vectorized function from def add(x, y): return x + y?
Avec_add = np.add(add)
Bvec_add = np.vectorize(add)
Cvec_add = np.vectorize(x + y)
Dvec_add = np.vectorize()
What happens if you pass multiple arrays to a vectorized function?
AIt applies the function element-wise across all arrays
BIt only uses the first array
CIt raises an error
DIt concatenates the arrays
Which statement is true about np.vectorize()?
AIt replaces all NumPy vectorized functions
BIt only works with built-in NumPy functions
CIt always improves code speed
DIt is a convenience wrapper for element-wise operations
Explain how np.vectorize() works and when you might use it.
Think about applying your own function to each item in a list or array.
You got /3 concepts.
    Describe a simple example using np.vectorize() with a custom function that takes two inputs.
    Imagine adding or multiplying two arrays element by element.
    You got /4 concepts.