a = np.zeros((100,100,20))
。我想对每个x,y
位置执行一个涉及所有元素的z
轴操作,并将结果存储在一个与相应的x,y
位置相同的数组中,例如b = np.zeros((100,100))
。现在我正在使用for循环来实现:
d_n = np.array([...]) # a parameter with the same shape as b
for (x,y), v in np.ndenumerate(b):
C = a[x,y,:]
### calculate some_value using C
minv = sys.maxint
depth = -1
C = a[x,y,:]
for d in range(len(C)):
e = 2.5 * float(math.pow(d_n[x,y] - d, 2)) + C[d] * 0.05
if e < minv:
minv = e
depth = d
some_value = depth
if depth == -1:
some_value = len(C) - 1
###
b[x,y] = some_value
现在的问题是,这种操作比其他用Pythonic方式完成的操作要慢得多,例如
c = b * b
(实际上我对这个函数进行了剖析,它比使用numpy内置函数和矢量化函数处理相似数量元素的其他函数慢了约两个数量级)。如何提高将3D数组映射到2D数组的此类函数的性能?
d_n
是什么意思? - Jaimeb
形状相同的参数,只是修改了示例。 - ButterDog