Instagram
youtube
Facebook
Twitter

Apply Function to Each Element in NumPy Array

Apply Function to Each Element in NumPy Array?
Code Explanation:
Library Import:
numpy is imported as np to use array operations.
Create Array: arr is a NumPy array with integer values.
Define Function: A lambda function lambda x: x**2 is used to square each element.
Apply Function: np.vectorize() allows the lambda function to work element-wise on the array.
Function Execution: The vectorized function is called with (arr) to apply it to each element.
Store Result: The squared results are stored in the variable squared.
Display Output: print(squared) prints the array with squared values.

 

Program:

import numpy as np

arr = np.array([1, 2, 3, 4])

squared = np.vectorize(lambda x: x**2)(arr)

print(squared)