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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:15:20  来源:igfitidea点击:

How to select all elements in a NumPy array except for a sequence of indices

pythonarraysnumpy

提问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.deletedoes. (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.deletedoes 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.in1dor np.isinto create boolean index based on excludecould be an alternative:

np.in1dnp.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])