Python:当更改相同时,是否有更快的方法来修改相同形状的多个数组?

vnjpjtjt  于 2022-12-17  发布在  Python
关注(0)|答案(2)|浏览(105)

我有多个numpy数组,它们都是相同的形状,我有两个面具也是相同的形状。
现在我一次改变一个数组,有没有更快的方法?
这是我正在做的一个小规模的例子。

start = time.time()

mask1 = np.array([[1,0,1],[0,1,1],[1,0,1]])
mask2 = np.array([[0,0,0],[1,0,1],[0,0,1]])

arr1 = np.array([[20,10,51],[21,1,2],[25,23,38]])
arr2 = np.array([[99,1,6],[66,54,11],[22,21,1]])
arr3 = np.array([[23,2,3],[55,2,16],[90,37,1]])
arr4 = np.array([[81,25,22],[1,63,24],[47,58,1]])

arr1[(mask1 == 1) & (mask2 == 0)] = 9999
arr2[(mask1 == 1) & (mask2 == 0)] = 9999
arr3[(mask1 == 1) & (mask2 == 0)] = 9999
arr4[(mask1 == 1) & (mask2 == 0)] = 9999

print(time.time() - start)
t1qtbnec

t1qtbnec1#

在@hpaulj的建议下,我做了以下几点,看到了一些改进!

import timeit

def func1():
    mask1 = np.array([[1,0,1],[0,1,1],[1,0,1]])
    mask2 = np.array([[0,0,0],[1,0,1],[0,0,1]])
    arr1 = np.array([[20,10,51],[21,1,2],[25,23,38]])
    arr2 = np.array([[99,1,6],[66,54,11],[22,21,1]])
    arr3 = np.array([[23,2,3],[55,2,16],[90,37,1]])
    arr4 = np.array([[81,25,22],[1,63,24],[47,58,1]])
    arr1[(mask1 == 1) & (mask2 == 0)] = 9999
    arr2[(mask1 == 1) & (mask2 == 0)] = 9999
    arr3[(mask1 == 1) & (mask2 == 0)] = 9999
    arr4[(mask1 == 1) & (mask2 == 0)] = 9999

def func2():
    mask1 = np.array([[1,0,1],[0,1,1],[1,0,1]])
    mask2 = np.array([[0,0,0],[1,0,1],[0,0,1]])
    mask1[(mask1==1) & (mask2 != 0)] = 0
    arr1 = np.array([[20,10,51],[21,1,2],[25,23,38]])
    arr2 = np.array([[99,1,6],[66,54,11],[22,21,1]])
    arr3 = np.array([[23,2,3],[55,2,16],[90,37,1]])
    arr4 = np.array([[81,25,22],[1,63,24],[47,58,1]])
    arr1[(mask1 == 1)] = 9999
    arr2[(mask1 == 1)] = 9999
    arr3[(mask1 == 1)] = 9999
    arr4[(mask1 == 1)] = 9999

print(timeit.timeit(func1, number=1000000))
#17.574998669995693

print(timeit.timeit(func2, number=1000000))
#15.318040108977584
2uluyalo

2uluyalo2#

我想说的是:

mask3 = (mask1 == 1) & (mask2 == 0)    
arr1[mask3] = 9999
arr2[mask3] = 9999
arr3[mask3] = 9999
arr4[mask3] = 9999

相关问题