簡體   English   中英

替換 Boolean Numpy 數組中 True 項的百分比

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

我有一個 numpy 數組,它可能看起來像:

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

我需要根據概率將True值替換為TrueFalse 例如,如果概率為 0.5,則其中一個將被替換為False 實際上,每個元素都會應用概率。

所以我有 numpy 在哪里。 但我不知道該怎么做:

其中value == True用隨機值替換。

假設你想要一個均勻的概率分布

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

這對我有用:

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