从数组的特定元素中选择随机元素

从数组的特定元素中选择随机元素

问题描述:

我有一个带有布尔值的1D(numpy)数组。例如:从数组的特定元素中选择随机元素

x = [True, True, False, False, False, True, False, True, True, True, False, True, True, False] 

该数组包含8真值。例如,我想保留3(在这种情况下必须小于8)作为从8存在的随机True值。换句话说,我想随机设置5那些8的真值作为False。

一个可能的结果可能是:

x = [True, True, False, False, False, False, False, False, False, False, False, False, True, False] 

如何实现的呢?

+1

到目前为止,您已经做了什么来尝试解决问题?困难在哪里?你可以告诉我们你的代码,你试图实现这个? – Derek

+0

究竟应该是随机的?元素的数量(在你的情况3)还是新阵列中的位置?或者从数组'x'中选择哪些元素? – MSeifert

一种方法是 -

# Get the indices of True values 
idx = np.flatnonzero(x) 

# Get unique indices of length 3 less than the number of indices and 
# set those in x as False 
x[np.random.choice(idx, len(idx)-3, replace=0)] = 0 

采样运行 -

# Input array 
In [79]: x 
Out[79]: 
array([ True, True, False, False, False, True, False, True, True, 
     True, False, True, True, False], dtype=bool) 

# Get indices 
In [80]: idx = np.flatnonzero(x) 

# Set 3 minus number of True indices as False 
In [81]: x[np.random.choice(idx, len(idx)-3, replace=0)] = 0 

# Verify output to have exactly three True values 
In [82]: x 
Out[82]: 
array([ True, False, False, False, False, False, False, True, False, 
     False, False, True, False, False], dtype=bool) 
+0

@Divakar你明白我的完美,谢谢! – pyigal

+0

是的,这是有道理的。鉴于它被接受,我一定误解了这个问题。现在删除评论:) – MSeifert

建立与所需TrueFalse数量的数组,然后只是将它洗

import random 
def buildRandomArray(size, numberOfTrues): 
    res = [False]*(size-numberOfTrues) + [True]*numberOfTrues 
    random.shuffle(res) 
    return res 

Live example