0
0
NumPydata~5 mins

np.vectorize() for custom functions in NumPy

Choose your learning style9 modes available
Introduction

np.vectorize() helps apply your own function to each item in an array easily. It makes your code simpler and faster to write.

You want to apply a custom math operation to every number in a list or array.
You have a function that works on single values but want to use it on whole arrays.
You want to avoid writing loops to process each element one by one.
You want to keep your code clean and easy to read when working with arrays.
Syntax
NumPy
vectorized_function = np.vectorize(your_function)
result = vectorized_function(array)

np.vectorize() takes your function and returns a new function that works on arrays.

The original function should work on single values.

Examples
This example squares each element in the array using a custom function.
NumPy
import numpy as np

def square(x):
    return x * x

vec_square = np.vectorize(square)
arr = np.array([1, 2, 3])
print(vec_square(arr))
This example checks if each number in the array is even.
NumPy
import numpy as np

def is_even(x):
    return x % 2 == 0

vec_is_even = np.vectorize(is_even)
arr = np.array([1, 2, 3, 4])
print(vec_is_even(arr))
Sample Program

This program adds a text prefix to each number in the array using a custom function and np.vectorize.

NumPy
import numpy as np

def add_prefix(num):
    return f"Num_{num}"

vec_add_prefix = np.vectorize(add_prefix)
arr = np.array([10, 20, 30])
result = vec_add_prefix(arr)
print(result)
OutputSuccess
Important Notes

np.vectorize() is not always faster than loops but makes code cleaner.

It works by calling your function on each element internally.

Use it when you want easy array operations with custom logic.

Summary

np.vectorize() turns a function for single values into one that works on arrays.

It helps avoid writing explicit loops over arrays.

Use it to apply custom functions element-wise on numpy arrays.