假设我有一个很长的数组和一个索引列表,如何选择除了这些索引之外的所有内容?我找到了一个解决方案,但它并不优雅:
import numpy as np
x = np.array([0,10,20,30,40,50,60])
exclude = [1, 3, 5]
print x[list(set(range(len(x))) - set(exclude))]
假设我有一个很长的数组和一个索引列表,如何选择除了这些索引之外的所有内容?我找到了一个解决方案,但它并不优雅:
import numpy as np
x = np.array([0,10,20,30,40,50,60])
exclude = [1, 3, 5]
print x[list(set(range(len(x))) - set(exclude))]
这就是numpy.delete
的作用。(它不会修改输入的数组,所以您不必担心。)
In [4]: np.delete(x, exclude)
Out[4]: array([ 0, 20, 40, 60])
np.delete
根据输入的不同有多种用法,但在这种情况下,它使用类似于以下形式的掩码:
In [604]: mask = np.ones(x.shape, bool)
In [605]: mask[exclude] = False
In [606]: mask
Out[606]: array([ True, False, True, False, True, False, True], dtype=bool)
In [607]: x[mask]
Out[607]: array([ 0, 20, 40, 60])
np.in1d
或np.isin
可以创建基于exclude
的布尔索引,是一种替代方案:
x[~np.isin(np.arange(len(x)), exclude)]
# array([ 0, 20, 40, 60])
x[~np.in1d(np.arange(len(x)), exclude)]
# array([ 0, 20, 40, 60])
你也可以使用列表推导式来获取索引
>>> x[[z for z in range(x.size) if not z in exclude]]
array([ 0, 20, 40, 60])