根据numpy文件:numpy.bincount(x, weights=None, minlength=None)weights : array_like, optional;
Weights, array of the same shape as x.
所以你不能用这种方式直接使用bincount,除非你改变了x。在
编辑:所以我想出了一个稍微有点棘手的方法来实现这一点,但是对于大数组的性能却没有保证。基本上,我将利用scipy稀疏矩阵如何处理相同索引下的重复条目(它们求和):
^{pr2}$
现在你要把它推广到你的精确数据中。基本思想是将每个数据点映射到结果数组的正确元素,然后让稀疏数组处理重复项的求和。在
否则,如果你被迫使用循环来解决这个问题,我会考虑使用Cython。在
编辑2:对于踢腿,我计时了两种不同的方法:import numpy as np
from scipy.sparse import *
def method1():
return np.array([np.bincount(ii, r) for r in a.T]).T
def method2():
ares = a.reshape((-1,),order='F')
col = np.tile(ii,(a.shape[1],))
row = np.tile(np.arange(a.shape[1]),(a.shape[0],1)).reshape((-1,),order='F')
return coo_matrix((ares,(col,row)),shape=(np.unique(ii).size,a.shape[1])).todense()
if __name__ == '__main__':
from timeit import Timer
a = np.random.randint(0,1000,(1000000,3))
ii = np.random.randint(0,10,(a.shape[0],))
N = 100
t1 = Timer("method1()", "from __main__ import method1")
t2 = Timer("method2()", "from __main__ import method2")
print 't2/t1: %f' % (t2.timeit(N)/t1.timeit(N))
在我的机器上,method2大约比method1慢3-5倍,这取决于输入的形状,所以循环并不一定是个坏选择。在