如何使用Numpy对此循环进行矢量化?
count=0
arr1 = np.random.rand(184,184)
for i in range(arr1.size[0]):
for j in range(arr1.size[1]):
if arr1[i,j] > 0.6:
count += 1
print count
我试过了:
count=0
arr1 = np.random.rand(184,184)
mask = (arr1>0.6)
indices = np.where(mask)
print indices , len(indices)
我期望len(指数)给予计数,但它没有。请提出任何建议。
答案 0 :(得分:12)
获取一个布尔掩码并计算“True”:
(arr1 > 0.6).sum()
答案 1 :(得分:7)
np.count_nonzero
应该比总和快一点:
np.count_nonzero(arr1 > 0.6)
事实上,它快三倍
>>> from timeit import repeat
>>> kwds = dict(globals=globals(), number=10000)
>>>
>>> arr1 = np.random.rand(184,184)
>>>
>>> repeat('np.count_nonzero(arr1 > 0.6)', **kwds)
[0.15281831508036703, 0.1485864429268986, 0.1477385900216177]
>>> repeat('(arr1 > 0.6).sum()', **kwds)
[0.5286932559683919, 0.5260644309455529, 0.5260107989888638]
答案 2 :(得分:0)
您还可以使用 Numpy 数组的 size 属性:
arr1 = np.random.rand(184,184)
arr1[ arr1 > 0.6 ].size