比较两个numpy数组并删除元素 [英] Comparing two numpy arrays and removing elements

查看:151
本文介绍了比较两个numpy数组并删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究几种解决方案,但是找不到所需的解决方案.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆