比较两个numpy数组并删除元素 [英] Comparing two numpy arrays and removing elements
问题描述
我一直在研究几种解决方案,但是找不到所需的解决方案.
I have been going through several solutions, but I am not able to find a solution I need.
我有两个numpy
数组.让我们在这里举一个小例子.
I have two numpy
arrays. Let's take a small example here.
x = [1,2,3,4,5,6,7,8,9]
y = [3,4,5]
我想比较x和y,并删除那些在y中的x值.
I want to compare x and y, and remove those values of x that are in y.
所以我希望我的final_x是
So I expect my final_x to be
final_x = [1,2,6,7,8,9]
我发现 np.in1d 返回一个与x
长度相同的布尔数组,如果x
的元素位于y
中,则该数组为True,否则为False.但是,如果没有其他方法来获取我的final_x
,我该如何使用它呢?
I found out that np.in1d returns a boolean array the same length as x
that is True where an element of x
is in y
and False otherwise. But how do I use it, if not any other method to get my final_x
.??
推荐答案
简单地将由np.in1d
返回的布尔数组的取反版本传递给数组x
:
Simply pass the negated version of boolean array returned by np.in1d
to array x
:
>>> x = np.array([1,2,3,4,5,6,7,8,9])
>>> y = [3,4,5]
>>> x[~np.in1d(x, y)]
array([1, 2, 6, 7, 8, 9])
这篇关于比较两个numpy数组并删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!