I have a np.ndarray as follows:
[[ inf 1. 3. 2. 1.]
[ inf inf 2. 3. 2.]
[ inf inf inf 5. 4.]
[ inf inf inf inf 1.]
[ inf inf inf inf inf]]
Is there a way to get the indices and values of the m smallest items in that nd array? So, if I wanted the 4 smallest it would be
[(0,1,1),(0,4,1),(3,4,1),(0,3,2)]
where (row,col,val) is the notation above.
If there are multiple values then one of them is just randomly chosen. For instance, there were 3 ones and then next smallest is a value 2 but (0,3,2), (1,2,2),(1,4,2) were all possible choices.
Essentially, Can I extract the k smallest values in that format from the upper triangular matrix efficiently (the matrix is much larger than the example above). I tried flattening it, using square form, nsmallest, but am having trouble getting the indices and values to align. Thanks!
np.dstack(np.unravel_index(np.argsort(tri.ravel()), arr.shape))
All that's left is zipping the values on. – Confessedly