我有一个numpy数组,看起来可能像这样:
matches = np.array([True, True, False, False, False])
我需要根据概率用True
或True
替换False
值。例如,如果概率为0.5,则一个或另一个将被False
取代。实际上,每个元素都会应用概率。
所以我在哪里有麻木。但是我不知道该怎么做:
将value == True
替换为随机值。
答案 0 :(得分:2)
假设您想要均匀的概率分布
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
答案 1 :(得分:0)
这对我有用:
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)