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

Python 从数组的特定元素中选择随机元素,python,arrays,numpy,random,Python,Arrays,Numpy,Random,我有一个带有布尔值的1D(numpy)数组。例如: x = [True, True, False, False, False, True, False, True, True, True, False, True, True, False] 数组包含8True值。例如,我想将3(在本例中必须小于8)作为存在的8中的真实值随机保留。换句话说,我想将那些8真值中的5随机设置为False 可能的结果是: x = [True, True, False, False, False, False, Fal

我有一个带有布尔值的1D(numpy)数组。例如:

x = [True, True, False, False, False, True, False, True, True, True, False, True, True, False]
数组包含
8
True值。例如,我想将
3
(在本例中必须小于
8
)作为存在的
8
中的真实值随机保留。换句话说,我想将那些
8
真值中的
5
随机设置为False

可能的结果是:

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

如何实现它?

一种方法是-

# 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)

用所需的
True
False
数量构建一个数组,然后将其洗牌

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

到目前为止,您自己做了哪些尝试来解决问题?困难在哪里?你能告诉我们你的代码,你已经尝试实现这一点吗?到底什么应该是随机的?元素的数量(在您的案例3中)或新阵列中的位置?或者从数组
x
中选择哪些元素?@Divakar您完全理解我的意思,谢谢!是的,这是有道理的。既然它被接受了,我一定是误解了这个问题。正在删除注释:)