由于关注性能并使用两种方法,因此可以添加一些方法。一种方法是获取有效的布尔数组并转换为int
数据类型与.astype() method。另一种方法可能涉及使用np.where这让我们可以选择0
and 1
基于相同的布尔数组。因此,本质上我们有两种方法,一种利用高效的数据类型转换,另一种使用选择标准。现在,可以通过两种方式获得布尔数组 - 一种使用简单比较,另一种使用np.logical_and。因此,有两种获取布尔数组的方法和两种将布尔数组转换为的方法int
数组,我们最终会得到下面列出的四种实现 -
out1 = ((aa>0.5) & (bb>0.5)).astype(int)
out2 = np.logical_and(aa>0.5, bb>0.5).astype(int)
out3 = np.where((aa>0.5) & (bb>0.5),1,0)
out4 = np.where(np.logical_and(aa>0.5, bb>0.5), 1, 0)
您可以尝试使用数据类型来使用精度较低的类型,这不会有什么坏处,因为我们将值设置为0
and 1
反正。好处应该是显着的加速,因为它利用了内存效率。我们可以使用int8, uint8, np.int8, np.uint8 types。因此,前面列出的方法的变体使用新的int
数据类型是 -
out5 = ((aa>0.5) & (bb>0.5)).astype('int8')
out6 = np.logical_and(aa>0.5, bb>0.5).astype('int8')
out7 = ((aa>0.5) & (bb>0.5)).astype('uint8')
out8 = np.logical_and(aa>0.5, bb>0.5).astype('uint8')
out9 = ((aa>0.5) & (bb>0.5)).astype(np.int8)
out10 = np.logical_and(aa>0.5, bb>0.5).astype(np.int8)
out11 = ((aa>0.5) & (bb>0.5)).astype(np.uint8)
out12 = np.logical_and(aa>0.5, bb>0.5).astype(np.uint8)
运行时测试(因为我们在这篇文章中关注的是性能)-
In [17]: # Input arrays
...: aa = np.random.rand(1000,1000)
...: bb = np.random.rand(1000,1000)
...:
In [18]: %timeit ((aa>0.5) & (bb>0.5)).astype(int)
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype(int)
...: %timeit np.where((aa>0.5) & (bb>0.5),1,0)
...: %timeit np.where(np.logical_and(aa>0.5, bb>0.5), 1, 0)
...:
100 loops, best of 3: 9.13 ms per loop
100 loops, best of 3: 9.16 ms per loop
100 loops, best of 3: 10.4 ms per loop
100 loops, best of 3: 10.4 ms per loop
In [19]: %timeit ((aa>0.5) & (bb>0.5)).astype('int8')
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype('int8')
...: %timeit ((aa>0.5) & (bb>0.5)).astype('uint8')
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype('uint8')
...:
...: %timeit ((aa>0.5) & (bb>0.5)).astype(np.int8)
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype(np.int8)
...: %timeit ((aa>0.5) & (bb>0.5)).astype(np.uint8)
...: %timeit np.logical_and(aa>0.5, bb>0.5).astype(np.uint8)
...:
100 loops, best of 3: 5.6 ms per loop
100 loops, best of 3: 5.61 ms per loop
100 loops, best of 3: 5.63 ms per loop
100 loops, best of 3: 5.63 ms per loop
100 loops, best of 3: 5.62 ms per loop
100 loops, best of 3: 5.62 ms per loop
100 loops, best of 3: 5.62 ms per loop
100 loops, best of 3: 5.61 ms per loop
In [20]: %timeit 1 * ((aa > 0.5) & (bb > 0.5)) #@BPL's vectorized soln
100 loops, best of 3: 10.2 ms per loop