Python apply function to numpy array

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.

Frequently Asked:

Apply a function over a NumPy Array using vectorized function

The numpy module has a vectorize class. It takes a python function as 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

  • 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)
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.

Читайте также:  Java наименьшее целое число

Syntax of map() function

  • 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,

  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)
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.

  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)
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.

  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)
The original array : [1 2 3 4 5] The array after applying function : [11 12 13 14 15]

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.

Читайте также:  Html скрипт поисковой системы

Share your love

Leave a Comment Cancel Reply

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

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Как сопоставить функцию с массивом NumPy (с примерами)

Вы можете использовать следующий базовый синтаксис для сопоставления функции с массивом NumPy:

#define function my_function = lambda x: x\*5 #map function to every element in NumPy array my_function(my_array) 

В следующих примерах показано, как использовать этот синтаксис на практике.

Пример 1: Функция карты над одномерным массивом NumPy

В следующем коде показано, как сопоставить функцию с массивом NumPy, который умножает каждое значение на 2, а затем добавляет 5:

import numpy as np #create NumPy array data = np.array([1, 3, 4, 4, 7, 8, 13, 15]) #define function my_function = lambda x: x\*2+5 #apply function to NumPy array my_function(data) array([ 7, 11, 13, 13, 19, 21, 31, 35]) 

Вот как было рассчитано каждое значение в новом массиве:

  • Первое значение: 1*2+5 = 7
  • Второе значение: 3*2+5 = 11
  • Третье значение: 4*2+5 = 13
Читайте также:  Django на METANIT.COM

Пример 2: Функция Map над многомерным массивом NumPy

В следующем коде показано, как сопоставить функцию с многомерным массивом NumPy, который умножает каждое значение на 2, а затем добавляет 5:

import numpy as np #create NumPy array data = np.array([[1, 2, 3, 4], [5, 6, 7, 8]]) #view NumPy array print(data) [[1 2 3 4] [5 6 7 8]] #define function my_function = lambda x: x\*2+5 #apply function to NumPy array my_function(data) array([[ 7, 9, 11, 13], [15, 17, 19, 21]]) 

Обратите внимание, что этот синтаксис работал с многомерным массивом точно так же, как и с одномерным массивом.

Дополнительные ресурсы

В следующих руководствах объясняется, как выполнять другие распространенные операции в NumPy:

Источник

Map a Function in NumPy

Map a Function in NumPy

  1. Map a Function in NumPy With the numpy.vectorize() Function
  2. Map a Function in NumPy With the lambda Keyword in Python

This tutorial will introduce the methods to map a function over a NumPy array in Python.

Map a Function in NumPy With the numpy.vectorize() Function

The numpy.vectorize() function maps functions on data structures that contain a sequence of objects like arrays in Python. It successively applies the input function on each element of the sequence or array. The return-type of the numpy.vectorize() function is determined by the input function. See the following code example.

import numpy as np  array = np.array([1, 2, 3, 4, 5])  def fun(e):  return e%2  vfunc = np.vectorize(fun)  result = vfunc(array) print(result) 

We first created the array with the np.array() function and declared the function fun . Then we passed the fun function to the np.vectorize() function and stored the result in vfunc . After that, we passed the array to the vfunc and stored the result inside the result array.

Map a Function in NumPy With the lambda Keyword in Python

The lambda keyword creates an anonymous function in Python. Anonymous functions are helpful when we only need a function temporarily in our code. We can also use the lambda functions to map a function over a NumPy array. We can pass an array to the lambda function to apply iteratively over each array element.

import numpy as np  array = np.array([1, 2, 3, 4, 5])  lfunc = lambda e: e % 2  result = lfunc(array) print(result) 

We first created the array with the np.array() function and the lambda function lfunc with the lambda keyword. We then mapped the lfunc to the array by passing array to the lfunc function. We saved the result inside the result array and printed the values inside it.

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Источник

Оцените статью