numpy的唯一,没有排序 [英] numpy unique without sort

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

问题描述

如何使用numpy unique而不对结果进行排序,而仅按它们在序列中出现的顺序排序?像这样吗?

How can I use numpy unique without sorting the result but just in the order they appear in the sequence? Something like this?

a = [4,2,1,3,1,2,3,4]

np.unique(a) = [4,2,1,3]

而不是

np.unique(a) = [1,2,3,4]

使用朴素的解决方案应该可以编写一个简单的函数.但是,由于我需要多次执行此操作,所以有什么快速而整洁的方法吗?

Use naive solution should be fine to write a simple function. But as I need to do this multiple times, are there any fast and neat way to do this?

推荐答案

您可以使用return_index参数执行此操作:

You can do this with the return_index parameter:


>>> import numpy as np
>>> a = [4,2,1,3,1,2,3,4]
>>> np.unique(a)
array([1, 2, 3, 4])
>>> indexes = np.unique(a, return_index=True)[1]
>>> [a[index] for index in sorted(indexes)]
[4, 2, 1, 3]

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

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