Reputation: 21137
weight dictionary: {1:0.1, 2:0.9}
(there is a 10% probability of an item with the value 1 of being selected, 90% with value 2)
exmple value row: [0, 0, 1, 0, 2, 1]
(the will only be 0s and values that are contained in the dictionary)
The output should be a randomly chosen index
For the example row, the probabilities of the index of being selected for each item in the row should be [0, 0, 0.05, 0, 0.9, 0.05]
(note that since the row contains two different 1
elements, each of them should have a prob of 0.05 of being selected, since the weight counts towards an item with that value being selected)
Upvotes: 2
Views: 85
Reputation: 20669
You can use np.select
here.
wt = {1:0.1, 2:0.9}
a = np.array([0, 0, 1, 0, 2, 1])
choicelist = [a==i for i in wt.keys()]
condlist = [v/np.count_nonzero(a==k) for k,v in wt.items()]
np.select(choicelist, condlist)
# array([0. , 0. , 0.05, 0. , 0.9 , 0.05])
Upvotes: 3