📜  如何在 NumPy 数组上映射函数?

📅  最后修改于: 2022-05-13 01:55:25.527000             🧑  作者: Mango

如何在 NumPy 数组上映射函数?

在本文中,我们将了解如何在Python中将函数映射到 NumPy 数组。

方法一: numpy.vectorize() 方法

numpy.vectorize()函数将函数映射到包含一系列对象(如 NumPy 数组)的数据结构上。对象的嵌套序列或 NumPy 数组作为输入并返回单个 NumPy 数组或 NumPy 数组的元组。

Python3
import numpy as np
  
arr = np.array([1, 2, 3, 4, 5])
  
def addTwo(i):
    return i+2
    
applyall = np.vectorize(addTwo)
res = applyall(arr)
print(res)


Python3
import numpy as np
  
arr = np.array([1, 2, 3, 4, 5])
  
def applyall(i): 
  return i + 2
  
res = applyall(arr)
print(res)


Python3
import numpy as np
  
arr = np.array([1, 2, 3, 4, 5])
  
def applyall(a):
    return a+2
  
res = applyall(arr)
print(res)


输出:

[3 4 5 6 7]

说明:函数被传递给向量化方法,数组再次传递给它,函数将返回应用数组的数组。

方法二:使用 lambda函数

lambda 是一个匿名函数,它接受任意数量的参数,但只计算一个表达式。

Python3

import numpy as np
  
arr = np.array([1, 2, 3, 4, 5])
  
def applyall(i): 
  return i + 2
  
res = applyall(arr)
print(res)

输出:

[3 4 5 6 7]

方法 3:使用数组作为函数的参数来映射 NumPy 数组

只需将数组传递给函数,我们就可以将函数映射到 NumPy 数组上。

Python3

import numpy as np
  
arr = np.array([1, 2, 3, 4, 5])
  
def applyall(a):
    return a+2
  
res = applyall(arr)
print(res)

输出:

[3 4 5 6 7]

说明:数组被传递给 applyall() 方法,它将函数映射到整个数组并返回结果数组。