jeudi 25 avril 2019

Replace duplicate elements in a numpy array based on a range

I have an 1d numpy array arr as below:

arr = np.array([9, 7, 0, 4, 7, 4, 2, 2, 3, 7])

For the duplicate elements, I wish to randomly select any one of the indices containing the same element and replace it with a value missing in between 0 and arr.shape[0].

e.g. In the given array, 7 is present in indices 1, 4 and 9. Hence, I wish to randomly select an index between 1, 4 and 9 and set its value by randomly selecting some element like 8, which is absent in the array. In the end, arr should contain 10 unique elements lying between 0 and 9 (both inclusive)

How can I do this efficiently using Numpy (possibly without needing to use any explicit loop)?




Aucun commentaire:

Enregistrer un commentaire