![](/img/trans.png)
[英]Check if each element in a numpy array at its given position matches another element at the same position in a different array
[英]Check if each element in a numpy array is in another array
这个问题似乎很简单,但我无法完全找到一个不错的解决方案。 我有两个numpy数组(A和B),我想获取A的索引(其中A的元素在B中),还希望获取A的索引,其中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]
,即不在B
的A
元素的索引?
如果不是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()
使用sort,这对于大型数据集来说很慢。 如果数据集很大,则可以使用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
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])
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])
设置(A)和设置(B)
设置(A)-设置(B)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.