使用numpy setdiff1d保持顺序 [英] Use numpy setdiff1d keeping the order

查看:222
本文介绍了使用numpy setdiff1d保持顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = np.array([1, 2, 3])
b = np.array([4, 2, 3, 1, 0])
c = np.setdiff1d(b, a)
print("c", c)

结果是c [0, 4],但我想要的答案是c [4 0].

The result is c [0, 4] but the answer I want is c [4 0].

我该怎么做?

推荐答案

获取与np.in1d不匹配的掩码,并简单地将布尔值索引到b中以保留其中的元素顺序-

Get the mask of non-matches with np.in1d and simply boolean-index into b to retain the order of elements in it -

b[~np.in1d(b,a)]

示例分步运行-

In [14]: a
Out[14]: array([1, 2, 3])

In [15]: b
Out[15]: array([4, 2, 3, 1, 0])

In [16]: ~np.in1d(b,a)
Out[16]: array([ True, False, False, False,  True], dtype=bool)

In [17]: b[~np.in1d(b,a)]
Out[17]: array([4, 0])

这篇关于使用numpy setdiff1d保持顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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