Numpy切片:除了这些之外的所有条目

时间:2014-04-08 00:58:48

标签: numpy

我有一个numpy数组a。我想选择这个数组的随机样本作为交叉验证的测试和训练集。作为训练集,我通过选择条目idx来使用切片。有没有办法选择这些条目的赞美?即所有不在idx中的条目。

# N: size of numpy array a.
idx = random.sample(np.arange(N),N/10) # select random sample
train(a[idx]) # train on this random sample
test(a[ NOT idx]) # test on the rest. 

如何以最后一行的紧凑方式调用其余条目? 感谢。

1 个答案:

答案 0 :(得分:3)

如果你使idx成为一个布尔数组,那么你可以用~idx选择补语:

import numpy as np

N = len(a)
idx = np.zeros(N, dtype='bool')
idx[np.random.choice(np.arange(N), size=N/10, replace=False)] = True
train(a[idx]) # train on this random sample
test(a[~idx]) # test on the rest.