numpy:在排序数组中查找索引(一种有效的方式) [英] numpy: find index in sorted array (in an efficient way)

查看:453
本文介绍了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:在排序数组中查找索引(一种有效的方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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