python - 从有限制的列表中使用随机选择时解决 ValueError

标签 python numpy random valueerror

给定一个随机列表和一个限制列表:

>>> import numpy as np
>>> x = np.random.randint(0, 50, 10)
>>> x
array([27, 14, 42,  1,  9, 43, 16, 39, 27,  3])
>>> y = [1,2,5, 19, 27]
>>> n = 5

我想从 X 中采样(不替换)N 而没有 Y 中的值,我可以这样做:

>>> np.random.choice(list(set(x).difference(y)), n, replace=False)
array([39,  9, 43, 14, 16])

N 是肯定小于 len(x) 的用户输入,但鉴于我不知道 N 是否大于 X-Y 的子集,我可能会遇到这种情况一个ValueError:

>>> np.random.choice(list(set(x).difference(y)), 8, replace=False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "mtrand.pyx", line 1150, in mtrand.RandomState.choice (numpy/random/mtrand/mtrand.c:18113)
ValueError: Cannot take a larger sample than population when 'replace=False'

鉴于我必须为 N 预设一个最大值,例如:

>>> n = min(n, len(list(set(x).difference(y))) )
>>> n
7

但在那种情况下,N 不再是 8,用户输入:

>>> np.random.choice(list(set(x).difference(y)), n, replace=False)
array([14, 39, 43,  3, 42,  9, 16])

所以我必须后添加输出:

>>> list(np.random.choice(list(set(x).difference(y)), _n, replace=False)) + [-1]*(n-_n)
[43, 42, 9, 16, 3, 39, 14, -1]

总而言之,我要抽样N个。没有从不在 Y 中的 X 值的子集中替换的元素,如果子集的长度小于 N,我需要用 -1 填充“空白”。

我可以用上面的代码做到这一点,但是有没有更简洁(希望也更有效)的方法来实现相同的输出?

最佳答案

我可能会使用 np.in1d取差,然后np.append进行后处理:

x = np.random.randint(0, 50, 10)
y = [1, 2, 5, 19, 27]
n = 12    

x_y = x[~np.in1d(x,y)]                                                    
arr = np.append(np.random.choice(x_y, len(x_y), replace=False), [-1]*(n-len(x_y)))
print arr
# array([35, 46, 39, 21,  9, 37, 17, 23,  8, -1, -1, -1])

如果 n 小于差值的长度,则不会附加任何内容。

关于python - 从有限制的列表中使用随机选择时解决 ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42688431/

相关文章:

python - 如何使用美国农业部 API

jquery - 让具有类别的对象在循环中随机出现/消失

python - Pandas:使用重复值进行透视

python - 给定长度的数组的所有组合

python - 为什么 cv2.projectPoints 的行为不如我预期?

python - numpy 切片赋值

c# - 为什么 Random() 在 .Net 中以这种方式实现?

c - C 中的循环内循环和随机生成

python - 异步 : How to queue object when an exception occurs

python - convolve2d和filter2D之间的差异。为什么输出形状有所不同?