You can convert the R,C indices from idx to linear indices, and then find the unique ones along with their counts and finally save them in grids output as the final output. Here's the implementation to achieve the same -
# Calculate linear indices corressponding to idx lin_idx = idx[:,0]*U + idx[:,1] # Get unique linear indices and their counts unq_lin_idx,idx_counts = np.unique(lin_idx,return_counts=True) # Setup output array and store index counts in raveled/flattened version grids = np.zeros((U,U)) grids.ravel()[unq_lin_idx] = idx_counts
Runtime Tests -
The following are run-time tests covering all approaches (including @DSM suitable ) and using the same definitions that are specified in this solution -
In [63]: U = 100 ...: idx = np.floor(np.random.random(size=(5000,2))*U).astype(np.int) ...: In [64]: %timeit interadd(U, idx) 100 loops, best of 3: 7.57 ms per loop In [65]: %timeit interadd2(U, idx) 100 loops, best of 3: 2.59 ms per loop In [66]: %timeit interadd3(U, idx) 1000 loops, best of 3: 1.24 ms per loop In [67]: def unique_counts(U, idx): ...: lin_idx = idx[:,0]*U + idx[:,1] ...: unq_lin_idx,idx_counts = np.unique(lin_idx,return_counts=True) ...: grids = np.zeros((U,U)) ...: grids.ravel()[unq_lin_idx] = idx_counts ...: return grids ...: In [68]: %timeit unique_counts(U, idx) 1000 loops, best of 3: 595 ยตs per loop
Time series show that the proposed np.unique based np.unique more than 50% faster than the second fastest approach.
Divakar
source share