Python的numpy库对花式索引进行"矢量化"有时会产生意想不到的结果.例如:
import numpy
a = numpy.zeros((1000,4), dtype='uint32')
b = numpy.zeros((1000,4), dtype='uint32')
i = numpy.random.random_integers(0,999,1000)
j = numpy.random.random_integers(0,3,1000)
a[i,j] += 1
for k in xrange(1000):
b[i[k],j[k]] += 1
Run Code Online (Sandbox Code Playgroud)
在数组'a'和'b'中给出不同的结果(即,无论重复如何,元组(i,j)的外观在'a'中显示为1,而重复在'b'中计数).这很容易验证如下:
numpy.sum(a)
883
numpy.sum(b)
1000
Run Code Online (Sandbox Code Playgroud)
值得注意的是,花式索引版本比for循环快了近两个数量级.我的问题是:"在提供的示例中使用for循环实现的numpy计算重复计数是否有效?"