检查numpy数组中的每个元素是否在另一个数组中 [英] Check if each element in a numpy array is in another array
本文介绍了检查numpy数组中的每个元素是否在另一个数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题似乎很简单,但我无法完全找到一个不错的解决方案.我有两个numpy数组(A和B),我想获取A的索引(其中A的元素在B中),还要获取A的索引,其中A的元素不在B中.
This problem seems easy but I cannot quite get a nice-looking solution. I have two numpy arrays (A and B), and I want to get the indices of A where the elements of A are in B and also get the indices of A where the elements are not in 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
元素的索引)?
which takes advantage of the fact that A
is in order, and gives me [1, 3, 5]
, the indices of the elements that are in A
. This is great, but how do I get D = [0,2,4,6]
, the indices of elements of A
that are not in B
?
推荐答案
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])
这篇关于检查numpy数组中的每个元素是否在另一个数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文