Apply a function to every element in NumPy Array

In this article, we will learn how to apply a method over a NumPy Array in Python.

Table Of Contents

Given a NumPy array we need to apply the function to each and every element of the array.

For Example: Applying an add() function to a NumPy Array, which adds 10 to the given number,

    Given array = [1, 2, 3, 4, 5]
    After adding 10 to each element of array: [11, 12, 13, 14, 15]

There are multiple ways to to apply the function to each and every element of a NumPy Array. Lets discuss all the methods one by one with proper approach and a working code example.

Advertisements

Apply a function over a NumPy Array using vectorized function

The numpy module has a vectorize class. It takes a python function aas an argument and returns a vectorized function. This vectorized function takes a NumPy Array as argument and calls the earlier assigned function to each element of the array. Then returns a NumPy Array containing the result.

Syntax of vectorize

numpy.vectorize(pyfunc)
  • Parameters:
  • pyfunc = Python function or method.
  • Returns:
  • Returns a vectorized function.

First create a function which you want to apply over the array, then follow the following approach:

The Approach:

  1. Import numpy library and create numpy array.
  2. Create a function that you want to appply on each element of NumPy Array. For example function with name add().
  3. Pass this add() function to the vectorize class. It returns a vectorized function.
  4. Pass the NumPy Array to the vectorized function.
  5. The vectorized function will apply the the earlier assigned function ( add() ) to each element of the array and returns a NumPy Array containing the result.
  6. Print the Array.

Source Code

import numpy as np

# A function to be applied to the array
def add(num):
    return num + 10

# creating  numpy array
arr = np.array([1, 2, 3, 4, 5])

# printing the original array
print(" The original array : " , arr)

# Apply add() function to array. 
addTen = np.vectorize(add)
arr = addTen(arr)

# printing the array after applying function
print(" The array after applying function : " , arr)

Output:

 The original array :  [1 2 3 4 5]
 The array after applying function :  [11 12 13 14 15]

Apply a function over a NumPy Array using map() function

The python map() function takes function and an iterable as parameters. It then applies the given function on all elements of the given iterable and returns a mapped object. We can iterate over this mapped object to get all the result values or we can directly convert it into a list.

Syntax of map() function

map(function, iterator)
  • Parameters:
  • function = Python function or method.
  • iterator = List, set, tuple.
  • Returns:
  • Returns an iterator.

First create a function which you want to apply over the array, and follow the following approach,

Approach:

  1. Import numpy library and create numpy array.
  2. Create a function to add a number to the functional parameter.
  3. Pass this function and the array to the map() function. It will return a mapped object by applying function to each element of iterator.
  4. Convert mapped object to list
  5. Convert it into an array and print it.

Source Code

import numpy as np

# function to be applied to the array
def add(num):
    return num+10
# creating  numpy array
arr = np.array([1, 2, 3, 4, 5])

# printing the original array
print(" The original array : " , arr)

# Apply add() function to array. 
arr = np.array(list(map(add, arr)))

# printing the array after applying function
print(" The array after applying function : " , arr)

Output:

 The original array :  [1 2 3 4 5]
 The array after applying function :  [11 12 13 14 15]

Apply a function over a NumPy Array using Using for Loop

We can iterate over a NumPy array and apply the given function on each element one by one.

Approach:

  1. Import numpy library and create numpy array.
  2. Using a for loop and range() method iterate over the array.
  3. Apply the given funtion to the each element of the array
  4. Print the array.

Source Code

import numpy as np

# function to be applied to the array
def add(num):
    return num+10

# creating  numpy array
arr = np.array([1, 2, 3, 4, 5])

# printing the original array
print(" The original array : " , arr)

# Apply add() function to array. 
for i in range(0,len(arr)):
    arr[i] = add(arr[i])

# printing the array after applying function
print(" The array after applying function : " , arr)

Output:

 The original array :  [1 2 3 4 5]
 The array after applying function :  [11 12 13 14 15]

Apply a function over a NumPy Array using List Comprehension

The List comprehensions are used for creating new lists from iterables like tuples, strings, arrays, lists, They offer very small syntax. Now to apply a function all over the array. Use the List Comprehension to iterate over the array and apply the given function to each element of the numpy array.

Approach:

  1. Import numpy library and create numpy array.
  2. Using List Comprehension to iterate the array.
  3. Apply the given funtion to the each element of the array and get all results in a list.
  4. Convert it into NumPy Array and print it.

Source Code

import numpy as np

# A function to be applied to the array
def add(num):
    return num+10

# creating  numpy array
arr = np.array([1, 2, 3, 4, 5])

# Printing the original array
print(" The original array : " , arr)

# Apply add() function to array. 
arr = np.array([add(num) for num in arr])

# printing the array after applying function
print(" The array after applying function : " , arr)

Output:

The original array :  [1 2 3 4 5]
The array after applying function :  [11 12 13 14 15]

Summary

Great! you made it, We have discussed All possible methods to apply a method over all elements of a NumPy Array in Python. Happy learning.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top