简体   繁体   English

替换 Boolean Numpy 数组中 True 项的百分比

[英]Replace percentage of True items in Boolean Numpy Array

I have a numpy array that maybe looks like:我有一个 numpy 数组,它可能看起来像:

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

I need to replace the True values with True or False depending on a probability.我需要根据概率将True值替换为TrueFalse For example if the probability is 0.5 one or the other will get replaced with False .例如,如果概率为 0.5,则其中一个将被替换为False Actually each element will have the probability applied to it.实际上,每个元素都会应用概率。

So I have numpy where.所以我有 numpy 在哪里。 But I cant quite figure out how to do it:但我不知道该怎么做:

Where value == True replace with random value.其中value == True用随机值替换。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM