一个简单的numpy索引示例:
In: a = numpy.arange(10)
In: sel_id = numpy.arange(5)
In: a[sel_id]
Out: array([0,1,2,3,4])
如何返回未由sel_id索引的其余数组?我能想到的是:
In: numpy.array([x for x in a if x not in a[id]])
out: array([5,6,7,8,9])
有没有更简单的方法?
对于这种简单的一维案例,我实际上使用了布尔掩码:
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))])
现在您可以获取您的值:
included = a[mask] # array([0, 1, 2, 3])
excluded = a[~mask] # array([4, 5, 6, 7, 8, 9])
请注意,a[mask]
不一定会产生与a[include_index]
相同的结果,因为在这种情况下,include_index
的顺序对于输出很重要(它应大致等于a[sorted(include_index)]
)。但是,由于未明确定义排除项目的顺序,因此应该可以。
编辑
创建蒙版的更好方法是:
mask = np.zeros(a.shape,dtype=bool)
mask[include_idx] = True
(感谢seberg)。
您可以使用布尔型蒙版很好地做到这一点:
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]
添加(来自@mgilson)。创建的二进制掩码可以很好地用于以a[~mask]
取回原始切片,但是只有原始索引为sorted时,这才是相同的。
EDIT:
下移,因为我必须意识到此时我会考虑np.delete
越野车。您也可以使用np.delete
,尽管遮罩功能更强大(将来我认为应该可以选择)。但是,现在它的速度比上述速度慢,并且将创建带有负索引的意外结果(或在给定切片时出现步长)。
print np.delete(a, [7,2,8])
更像是:
我会使用布尔型掩码来执行此操作,但有所不同。这样做的好处是可以在N维中使用连续或不连续的索引。内存使用情况取决于是否为蒙版数组创建视图或副本,我不确定。
numpy.setdiff1d(a, a[sel_id])
应该可以解决问题。不知道是否有比这更整洁的东西。
[此外,如果它们是连续的,请使用[N:]语法选择其余部分。例如,arr [5:]将选择数组中倒数第五个元素。
这是另一种方法,使用numpy的isin()
函数:
假设a
是一维数组,您可以只从索引列表中弹出不需要的项目: