numpy:在排序数组中查找索引(一种有效的方式)

编程入门 行业动态 更新时间:2024-10-25 08:22:48
本文介绍了numpy:在排序数组中查找索引(一种有效的方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想对一个numpy数组进行排序,并找出每个元素的去向.

I would like to sort a numpy array and find out where each element went.

numpy.argsort 会告诉我排序数组中的每个索引,未排序数组中的哪个索引在那里.我正在寻找相反的东西:对于未排序数组中的每个索引,它在已排序数组中的位置.

numpy.argsort will tell me for each index in the sorted array, which index in the unsorted array goes there. I'm looking for something like the inverse: For each index in the unsorted array, where does it go in the sorted array.

a = np.array([1, 4, 2, 3]) # a sorted is [1,2,3,4] # the 1 goes to index 0 # the 4 goes to index 3 # the 2 goes to index 1 # the 3 goes to index 2 # desired output [0, 3, 1, 2] # for comparison, argsort output [0, 2, 3, 1]

一个简单的解决方案使用 numpy.searchsorted

A simple solution uses numpy.searchsorted

np.searchsorted(np.sort(a), a) # produces [0, 3, 1, 2]

我对此解决方案不满意,因为它似乎效率很低.它通过两个单独的步骤进行排序和搜索.

I'm unhappy with this solution, because it seems very inefficient. It sorts and searches in two separate steps.

对于带有重复项的数组,此奇特索引失败,请查看:

This fancy indexing fails for arrays with duplicates, look at:

a = np.array([1, 4, 2, 3, 5]) print(np.argsort(a)[np.argsort(a)]) print(np.searchsorted(np.sort(a),a)) a = np.array([1, 4, 2, 3, 5, 2]) print(np.argsort(a)[np.argsort(a)]) print(np.searchsorted(np.sort(a),a))

推荐答案

您只需要反转排列的排序 .如链接的问题所示,您可以这样做:

You just need to invert the permutation that sorts the array. As shown in the linked question, you can do that like this:

import numpy as np def sorted_position(array): a = np.argsort(array) a[a.copy()] = np.arange(len(a)) return a print(sorted_position([0.1, 0.2, 0.0, 0.5, 0.8, 0.4, 0.7, 0.3, 0.9, 0.6])) # [1 2 0 5 8 4 7 3 9 6]

更多推荐

numpy:在排序数组中查找索引(一种有效的方式)

本文发布于:2023-11-30 21:32:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651534.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序数   组中   索引   方式   numpy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!