np.vectorize是将操作数字的Python函数转换为操作ndarray的numpy函数的通用方法。
但是,正如您所指出的那样,它并不是很快,因为它使用“后台”的Python循环。
为了获得更好的速度,您必须手工制作一个函数,该函数期望将numpy数组作为输入并利用该numpy-ness:
import numpy as npdef func2(x, y): return np.where(x>y,x+y,x-y)x = np.array([-2, -1, 0, 1, 2])y = np.array([-2, -1, 0, 1, 2])xx = x[:, np.newaxis]yy = y[np.newaxis, :]print(func2(xx, yy))# [[ 0 -1 -2 -3 -4]# [-3 0 -1 -2 -3]# [-2 -1 0 -1 -2]# [-1 0 1 0 -1]# [ 0 1 2 3 0]]
关于性能:
test.py :
import numpy as npdef func2a(x, y): return np.where(x>y,x+y,x-y)def func2b(x, y): ind=x>y z=np.empty(ind.shape,dtype=x.dtype) z[ind]=(x+y)[ind] z[~ind]=(x-y)[~ind] return zdef func2c(x, y): # x, y= x[:, None], y[None, :] A, L= x+ y, x<= y A[L]= (x- y)[L] return AN=40x = np.random.random(N)y = np.random.random(N)xx = x[:, np.newaxis]yy = y[np.newaxis, :]
运行:
当N = 30时:
% python -mtimeit -s'import test' 'test.func2a(test.xx,test.yy)'1000 loops, best of 3: 219 usec per loop% python -mtimeit -s'import test' 'test.func2b(test.xx,test.yy)'1000 loops, best of 3: 488 usec per loop% python -mtimeit -s'import test' 'test.func2c(test.xx,test.yy)'1000 loops, best of 3: 248 usec per loop
当N = 1000时:
% python -mtimeit -s'import test' 'test.func2a(test.xx,test.yy)'10 loops, best of 3: 93.7 msec per loop% python -mtimeit -s'import test' 'test.func2b(test.xx,test.yy)'10 loops, best of 3: 367 msec per loop% python -mtimeit -s'import test' 'test.func2c(test.xx,test.yy)'10 loops, best of 3: 186 msec per loop
这似乎表明它
func2a比
func2c(快得
func2b非常慢)快。



