Numpy向量化排除的参数

问题描述

请让我以简单的方式解释Numpy向量化函数中排除参数的功能。

解决方法

有时您不希望迭代所有对象。两个例子:

函数中的

f(a,b)用于单个元素,例如np.mod(a,b)。在这里矢量化没问题:

import numpy as np

vc = np.vectorize(np.mod)
print(vc([5,11,7,4],2)) # first element will be iterated
print(vc([5,[2,3,4,5])) # both elements will be iterated
print(vc(5,5])) # only second element will be iterated
另一方面,您有一个函数g(a,b),该函数需要b的数组(例如:查找表或多项式的参数)。因此b必须保留一个数组,否则该函数将给出错误或错误数据。这是通过排除b来完成的。请注意,通过使用exclude,现在必须命名所有参数。示例:
import numpy as np

def g(x,p):
  return p[0]+x*p[1]+x*x*p[2]

print(g(5,[0,1]))

vg = np.vectorize(g,excluded=['p'])
print(vg(x=[0,1,2,5],p=[0,1])) # p will not be iterated

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...