替换布尔型Numpy数组中True项目的百分比

时间:2020-07-13 09:27:47

标签: python numpy

我有一个numpy数组,看起来可能像这样:

matches = np.array([True, True, False, False, False])

我需要根据概率用TrueTrue替换False值。例如,如果概率为0.5,则一个或另一个将被False取代。实际上,每个元素都会应用概率。

所以我在哪里有麻木。但是我不知道该怎么做:

value == True替换为随机值。

2 个答案:

答案 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)