Apply the Numpy function to Each Element

In this blog, our users will get to learn how they can apply the Numpy function to each element present in the array. It is one of the basic functionality of the Numpy library of python programming language. The major advantage of using this functionality is that one does not need to apply the function individually on each element of the array. It not only saves time but as well makes your code more optimized.

 

 

Apply the Numpy function to each element

There is one of the most common methods to achieve the same. The first one is by using vectorized function. The code for the same is:

 

import numpy as np
# a formula to be used with the array
def add(num):
    return num + 10
# the numpy array creation
arr = np.array([1, 2, 3, 4, 5])
# the original array being printed
print(" The original array : " , arr)
# Apply the array's add() function.
addTen = np.vectorize(add)
arr = addTen(arr)
# printing the array once a function has been applied
print(" The array after applying function : " , arr)

 

Output

 

The approach for the same is:

  • Create a numpy array by importing the numpy library.
  • Make a function that you want to apply to each NumPy array element. Using the function add as an example ().
  • Pass the vectorize class this add() function. A vectorized function is what it returns.
  • The vectorized function should receive the NumPy Array.
  • Each element of the array will have the previously assigned function (add()) applied to it by the vectorized function, which then returns a NumPy Array holding the outcome.
  • Display the Array.

 

This is one of the basic approaches for applying the function of numpy on the whole array. 

 

 

Also Read: Python Botocore

 

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *