【问题标题】:Choose random elements from specific elements of an array从数组的特定元素中选择随机元素
【发布时间】:2017-08-17 10:59:49
【问题描述】:

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

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

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

可能的结果是:

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

如何实现?

【问题讨论】:

  • 到目前为止,您为尝试自己解决问题做了哪些工作?困难在哪里?您能向我们展示您尝试使用的代码吗?
  • 究竟什么应该是随机的?元素的数量(在您的情况下为 3)或新数组中的位置?或者从你的数组x中挑选哪些元素?

标签: python arrays numpy random


【解决方案1】:

一种方法是 -

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

【讨论】:

  • @Divakar 你完全理解我的意思,谢谢!
  • 是的,这是有道理的。鉴于它已被接受,我一定误解了这个问题。现在删除 cmets :)
【解决方案2】:

用所需的TrueFalse 的数量构建一个数组,然后随机播放它

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

Live example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-23
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多