从numpy数组中随机选择行

时间:2015-12-19 11:16:25

标签: python numpy

我想从numpy数组中随机选择行。说我有这个数组 -

A = [[1, 3, 0],
     [3, 2, 0],
     [0, 2, 1],
     [1, 1, 4],
     [3, 2, 2],
     [0, 1, 0],
     [1, 3, 1],
     [0, 4, 1],
     [2, 4, 2],
     [3, 3, 1]]

要随机选择说6行,我这样做:

B = A[np.random.choice(A.shape[0], size=6, replace=False), :]

我想要另一个数组C,其中包含未在B中选择的行。

是否有一些内置方法可以做到这一点,还是我需要做一个暴力破解,用A行检查B行?

3 个答案:

答案 0 :(得分:1)

您可以使用布尔掩码并从与您一样长的整数数组中绘制随机索引。 ~是元素而不是:

idx = np.arange(A.shape[0])
mask = np.zeros_like(idx, dtype=bool)

selected = np.random.choice(idx, 6, replace=False)
mask[selected] = True

B = A[mask]
C = A[~mask]

答案 1 :(得分:1)

您可以通过切换一个混洗的行索引序列来生成任意数量的A行的随机分区:

ind = numpy.arange( A.shape[ 0 ] )
numpy.random.shuffle( ind )
B = A[ ind[ :6 ], : ]
C = A[ ind[ 6: ], : ]

如果您不想更改每个子集中行的顺序,可以对索引的每个切片进行排序:

B = A[ sorted( ind[ :6 ] ), : ]
C = A[ sorted( ind[ 6: ] ), : ]

(注意@MaxNoe提供的解决方案也保留了行顺序。)

答案 2 :(得分:0)

解决方案

这为您提供了选择的索引:

sel = np.random.choice(A.shape[0], size=6, replace=False)

B

B = A[sel]

获取所有未选择的索引:

unsel = list(set(range(A.shape[0])) - set(sel))

并将其用于C

C = A[unsel]

NumPy函数的变化

您可以使用此代码:

,而不是使用setlist
unsel2 = np.setdiff1d(np.arange(A.shape[0]), sel)

对于示例数组,纯Python版本:

%%timeit
unsel1 = list(set(range(A.shape[0])) - set(sel)) 

100000 loops, best of 3: 8.42 µs per loop

比NumPy版本更快:

%%timeit
unsel2 = np.setdiff1d(np.arange(A.shape[0]), sel)

10000 loops, best of 3: 77.5 µs per loop

对于较大的A,NumPy版本更快:

A = np.random.random((int(1e4), 3))
sel = np.random.choice(A.shape[0], size=6, replace=False)


%%timeit
unsel1 = list(set(range(A.shape[0])) - set(sel))

1000 loops, best of 3: 1.4 ms per loop


%%timeit
unsel2 = np.setdiff1d(np.arange(A.shape[0]), sel)

1000 loops, best of 3: 315 µs per loop
相关问题