我有这样的功能(我无法更改):
def myFunc(x, y):
nx = int(x)
ny = int(y)
Freq = 0.4
e0 = 1 * gen.noise2d(Freq * nx, Freq * ny)
return e0 + 500
现在,我正在尝试将np.ndarray
用于代码的其他部分,并一次在循环中传入x
和y
值:>
# passing in a particles which is an array like this:
# [[2,4], [5, 9], [2, 5]]
# this array would have more than 5000 pairs of x, y coordinates
def mapFunc(particles):
N = len(particles)
mask = []
distance = []
for i in range(N):
x = particles[i][0]
y = particles[i][1]
ground_dist = mapFunc(x, y)
# add in the distances to the ground
distance.append(ground_dist)
# add True if the ground is less than 50 feet away
mask.append(ground_dist < 50)
return distance, mask
是否有更好/更快/更有效的方法从我的np.ndarray
中获取值?我能以某种方式将整个花絮传给myFunc
吗?问题是int(x)
和int(y)
,不确定如何在数组中使用Python。
编辑1-myFunc的返回错误,应该使用e0加500
编辑2-gen.noise2d来自https://github.com/lmas/opensimplex,以“根据X,Y坐标生成2D OpenSimplex噪声。”
答案 0 :(得分:0)
如果满足以下两个条件,则可以完全向量化代码:
gen.noise2d
是可矢量化的(可能使用下面显示的技术)或可忽略的myFunc
是python函数,与用C编写的函数相反。您可以在int
的全局命名空间中对名称myFunc
进行猴子修补,以引用np.around
或np.trunc
。后者更接近int
当前在代码中的作用:
myFunc.__globals__['int'] = np.trunc
您可能需要修改myFunc.__globals__['gen']['noise2d']
的依赖项,或将其完全替换掉。另外,您可能想完全忽略noise2d
函数,因为它的结果似乎根本没有被使用。
现在,您可以按以下方式重写代码:
def mapFunc(particles):
particles = np.asarray(particles)
distance = myFunc(*particles.T)
mask = distance < 50
return distance, mask
第myFunc.__globals__['int'] = np.trunc
行将修改定义__dict__
的模块的myFunc
。如果您想在其他地方使用实数int
,这可能是一件坏事在那个模块中。由于__globals__
属性是只读的,因此可以使用原始代码和其他全局变量创建函数对象的副本。这可能是矫kill过正,所以我将把您链接到以下文章:How to create a copy of a python function。
也许更简单的解决方案是将另一个对象绑定到名称myFunc
,并将其分配给适当的模块?