我知道我们可以用下面的代码行创建一个布尔值的NumPy数组:
np.random.choice(a=[False, True], size=(N,))
但是如果我想指定这个随机数组有大约60%(或者更一般的k%)True价值观?
使用np.choice
的概率数组参数
import numpy as np
N = 100
res = np.random.choice(a=[False, True], size=(N,), p=[0.4, 0.6])
print(np.count_nonzero(res))
(指单次运行)
62
对于大型数组,使用np.random.choice
可能会非常慢。我建议使用
import numpy as np
N = 100_000
booleans = np.random.rand(N) < 0.6
np.random.rand
将在0.0
和1.0
之间产生均匀的随机数,并且比较将将0.6
下的所有数字设置为True
,从而为您提供一个包含大约60%True
值的数组。
如果你需要确切的比例,你可以这样做
k = 60 # 60%
booleans = np.zeros(shape=(N,), dtype=bool) # Array with N False
booleans[:int(k / 100 * N)] = True # Set the first k% of the elements to True
np.random.shuffle(booleans) # Shuffle the array
np.count_nonzero(booleans) # Exactly 60 000 True elements