This should do what you want:
np.bincount(np.ravel_multi_index((i, j), (1000, 4)), minlength=4000).reshape(1000, 4)
As a breakdown, ravel_multi_index
converts the index pairs indicated by i
and j
into integer indices in a C-flattened array; bincount
counts the number of times each value of 0..4000
appears in this index list; and reshape
converts the C-flattened array back to a 2d array.
As for performance, I measure it 200 times faster than "b", and 5 times faster than "a"; Your mileage may vary.
Since you need to write scores to an existing array a
, try the following:
u, inv = np.unique(np.ravel_multi_index((i, j), (1000, 4)), return_inverse=True) a.flat[u] += np.bincount(inv)
I am making this second method a little slower (2x) than "a", which is not too surprising since the unique
step will be slow.
source share