这个问题看起来很简单,但我不能得到一个好看的解决方案。我有两个numpy数组(A和B),我想要得到A的索引(其中A的元素在B中),以及A的索引(元素不在B中)。
所以,如果
A = np.array([1,2,3,4,5,6,7])
B = np.array([2,4,6])
目前我正在使用
C = np.searchsorted(A,B)
它利用了A
是有序的这一事实,并给出了[1, 3, 5]
,即A
中元素的索引。这很好,但是如何获得D = [0,2,4,6]
,即A
中不在B
中的元素的索引
发布于 2013-04-11 10:40:27
import numpy as np
A = np.array([1,2,3,4,5,6,7])
B = np.array([2,4,6])
C = np.searchsorted(A, B)
D = np.delete(np.arange(np.alen(A)), C)
D
#array([0, 2, 4, 6])
发布于 2013-04-11 11:51:42
如果B的每个元素都不在A中,则searchsorted
可能会给出错误的答案。您可以使用numpy.in1d
A = np.array([1,2,3,4,5,6,7])
B = np.array([2,4,6,8])
mask = np.in1d(A, B)
print np.where(mask)[0]
print np.where(~mask)[0]
输出为:
[1 3 5]
[0 2 4 6]
然而,in1d()
使用排序,这对于大型数据集来说很慢。如果您的数据集很大,则可以使用pandas:
import pandas as pd
np.where(pd.Index(pd.unique(B)).get_indexer(A) >= 0)[0]
下面是时间对比:
A = np.random.randint(0, 1000, 10000)
B = np.random.randint(0, 1000, 10000)
%timeit np.where(np.in1d(A, B))[0]
%timeit np.where(pd.Index(pd.unique(B)).get_indexer(A) >= 0)[0]
输出:
100 loops, best of 3: 2.09 ms per loop
1000 loops, best of 3: 594 µs per loop
发布于 2013-04-11 10:48:04
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7])
b = np.array([2, 4, 6])
c = np.searchsorted(a, b)
d = np.searchsorted(a, np.setdiff1d(a, b))
d
#array([0, 2, 4, 6])
https://stackoverflow.com/questions/15939748
复制相似问题