numpy random.choice未选中的元素

时间:2014-04-05 04:27:45

标签: python numpy random subset choice

我有一个数组A,如下所示:

import numpy as np
A = np.random.sample(100)

我想从A创建2个随机子集,如果我将它们组合在一起,我将获得A

inx = np.random.choice(np.arange(100), size=70, replace=False)
S1 = A[inx]

因此,S1是其中一个子集,现在我如何构造S2以包含A中不在S1中的所有元素;换句话说,S2 = A-S1。

3 个答案:

答案 0 :(得分:6)

设置操作可能会有所帮助:

S2 = A[list(set(range(100)) - set(inx))]

但您可能需要排序:

S2 = A[ sorted(list(set(range(100)) - set(inx))) ]

答案 1 :(得分:3)

(轻微:如果A可以有重复元素,选择索引的补充并且S2包含A中不包含在S1中的所有元素都不是一回事。)

我可能完全绕过索引,而是置换元素然后拆分结果:

>>> A = np.random.sample(10)
>>> S1, S2 = np.split(np.random.permutation(A), [7])
>>> S1
array([ 0.97128145,  0.5617039 ,  0.42625808,  0.39108218,  0.52366291,
        0.73606525,  0.5279909 ])
>>> S2
array([ 0.45652426,  0.38622805,  0.99084781])

但也有np.setdiff1d,所以如果你已经有S1

>>> S2 = np.setdiff1d(A, S1)
>>> S2
array([ 0.38622805,  0.45652426,  0.99084781])

答案 2 :(得分:0)

我认为这段代码与您尝试的相同。

A = np.random.sample(100)
T = A[:]
np.random.shuffle(T)

size = 70
S1 = T[:size]
S2 = T[size:]