Python 如何选择 NumPy 数组中除索引序列外的所有元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47540800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select all elements in a NumPy array except for a sequence of indices
提问by kilojoules
Say I have some long array and a list of indices. How can I select everything except those indices? I found a solution but it is not elegant:
假设我有一些长数组和一个索引列表。我怎样才能选择除这些索引之外的所有内容?我找到了一个解决方案,但它并不优雅:
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))]
回答by user2357112 supports Monica
This is what numpy.delete
does. (It doesn't modify the input array, so you don't have to worry about that.)
这就是numpy.delete
它的作用。(它不会修改输入数组,因此您不必担心。)
In [4]: np.delete(x, exclude)
Out[4]: array([ 0, 20, 40, 60])
回答by hpaulj
np.delete
does various things depending what you give it, but in a case like this it uses a mask like:
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])
回答by Psidom
np.in1d
or np.isin
to create boolean index based on exclude
could be an alternative:
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])
回答by percusse
You can also use a list comprehension for the index
您还可以对索引使用列表理解
>>> x[[z for z in range(x.size) if not z in exclude]]
array([ 0, 20, 40, 60])