我正在运行一些模拟,其中涉及反复将 2D Numpy 数组中的值与其“邻居”进行比较;例如。索引位置的值(y,x)
与索引位置的值进行比较(y-1,x)
来自同一个数组。
目前我正在使用这样的函数:
# example of the typical size of the arrays
my_array = np.ndarray((500,500))
shapey, shapex = my_array.shape
Yshape = (1, shapex)
Yzeros = np.zeros((1, shapex))
def syf(A, E=True):
if E == True:
return np.concatenate((A[1:], A[-1].reshape(Yshape)), axis=0)
else:
return np.concatenate((A[1:], Yzeros), axis=0)
shifted_array = syf(my_array)
difference_in_y = shifted_array - my_array
可以选择使用边缘值或零在数组边缘进行比较。这些功能还可以在任一轴的任一方向上执行此操作。
有人对更快的方法有什么建议吗?
我试过了np.roll
(慢得多)还有这个:
yf = np.ix_(range(shapey)[1:] + [shapey,], range(shapex))
shifted_array = my_array[yf]
这有点慢。
在需要运行 10 个小时的程序中,这些函数每秒被调用约 200 次,因此任何小的加速都会更受欢迎!
Thanks.
EDIT:
因此,如果每次调用移位函数时都需要相同的微分方法,那么下面的 Divakars 方法似乎会提供较小的加速,但是如果只需要移位数组,则该方法和我上面使用的方法似乎速度相同。