I have a numpy array that maybe looks like:
matches = np.array([True, True, False, False, False])
I need to replace the True
values with True
or False
depending on a probability. For example if the probability is 0.5 one or the other will get replaced with False
. Actually each element will have the probability applied to it.
So I have numpy where. But I cant quite figure out how to do it:
Where value == True
replace with random value.
Assuming you want a uniform probability distribution
import numpy as np
matches = np.array([True, True, False, False, False])
# Here you create an array with the same length as the number of True values in matches
random_values = np.random.uniform(low=0, high=100, size=(sum(matches)))
# Setting the threshold and checking which random values are lower.
# If they are higher or equal it returns False, if they are lower it returns True
threshold = 75
random_values_outcome = random_values < threshold
# Substituting the True entries in matches with corresponding entries from
# random_values_outcome
matches[matches == True] = random_values_outcome
This worked for me:
import numpy as np
import random
matches = np.array([True, True, False, False, False])
for position, value in np.ndenumerate(matches):
if value == True:
matches[position] = random.choice([True, False])
print(matches)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.