Removing Loops In Numpy For A Simple Matrix Assignment
How can I remove loops in this simple matrix assignment in order to increase performance? nk,ncol,nrow=index.shape for kk in range(0,nk): for ii in range(0,nrow): for jj
Solution 1:
If I understand it correctly, you are looking for this:
uniq, counter = np.unique(index, return_counts=True, axis=0)
The uniq
should give you unique set of x,y
s (x,y
will be flattened into a single array) and counter
corresponding number of repetitions in the array index
EDIT:
Per OP's comment below:
xx,yy = np.meshgrid(np.arange(ncol),np.arange(nrow))
idx, counts = np.unique(np.vstack((index.flatten(),np.repeat(yy.flatten(),nk),np.repeat(xx.flatten(),nk))), return_counts=True,axis=1)
counter[tuple(idx)] = counts
Post a Comment for "Removing Loops In Numpy For A Simple Matrix Assignment"