Assigning minimum value with duplicate indices in numpy

Viewed 80

I have a numpy array X, which I initialize:

X = np.ones(10) * 100

and I have an array of indices for X:

I = np.array([2,5,2,1,7,8,5,2])

and finally an array of values to assign to X at indices I:

V = np.array([4,3,5,2,6,2,4,1])

What is the most efficient way to assign the values to array X, ensuring that when there are duplicate indices in I, the minimum corresponding value in V is assigned.

That is, I would like the final value of X to be:

[100, 2, 1, 100, 100, 3, 100, 6, 2, 100]

Is there a vectorized way to do this? Or a method that would be efficient for large arrays? i.e. can I avoid using a loop? Thanks!

1 Answers

This works:

vs = np.argsort(v)
uniq_idx, uniq_vs_idx = np.unique(i[vs], return_index=True)
x[uniq_idx] = v[vs][uniq_vs_idx]
Related