Numpy Indexing:返回其余部分

CJL*_*Lam 19 python arrays indexing numpy scipy

numpy索引的简单示例:

In: a = numpy.arange(10)
In: sel_id = numpy.arange(5)
In: a[sel_id]
Out: array([0,1,2,3,4])
Run Code Online (Sandbox Code Playgroud)

如何返回未被sel_id索引的数组的其余部分?我能想到的是:

In: numpy.array([x for x in a if x not in a[id]])
out: array([5,6,7,8,9])
Run Code Online (Sandbox Code Playgroud)

有没有更简单的方法?

mgi*_*son 14

对于这个简单的1D情况,我实际上使用了一个布尔掩码:

a = numpy.arange(10)
include_index = numpy.arange(4)
include_idx = set(include_index)  #Set is more efficient, but doesn't reorder your elements if that is desireable
mask = numpy.array([(i in include_idx) for i in xrange(len(a))])
Run Code Online (Sandbox Code Playgroud)

现在你可以得到你的价值观:

included = a[mask]  # array([0, 1, 2, 3])
excluded = a[~mask] # array([4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)

注意,a[mask]不一定产生与该场景中输出事项a[include_index]的顺序相同的事物include_index(它应该大致相当于a[sorted(include_index)]).但是,由于排除项目的顺序没有明确定义,因此这应该可以正常工作.


编辑

创建掩码的更好方法是:

mask = np.zeros(a.shape,dtype=bool)
mask[include_idx] = True
Run Code Online (Sandbox Code Playgroud)

(感谢塞伯格).


seb*_*erg 5

你可以用布尔掩码很好地做到这一点:

a = numpy.arange(10)

mask = np.ones(len(a), dtype=bool) # all elements included/True.
mask[[7,2,8]] = False              # Set unwanted elements to False

print a[mask]
# Gives (removing entries 7, 2 and 8):
[0 1 3 4 5 6 9]
Run Code Online (Sandbox Code Playgroud)

添加(取自@mgilson)。创建的二进制掩码可以很好地用于取回原始切片,a[~mask]但是这仅在原始索引已排序时才相同。


编辑:向下移动,因为我必须意识到此时我会考虑np.delete越野车(2012 年 9 月)。

您也可以使用np.delete,尽管掩码功能更强大(我认为将来这应该是一个不错的选择)。然而,目前它比上面的慢,并且会产生带有负索引(或给定切片时的步骤)的意外结果。

print np.delete(a, [7,2,8])
Run Code Online (Sandbox Code Playgroud)