NumPy:取消/取消反向/降序排序 [英] NumPy: Unsort/undo a reverse/descending sort

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

问题描述

我可以对numpy数组进行就地反向排序(降序排序),但我还需要稍后能够对其进行取消排序(撤消)操作.

I can do an in-place reverse sort (descending sort) of a numpy array, but I also need to be able to unsort (undo) it later.

给出一个未排序的示例:

Given an unsorted example:

a = np.array([-1, -2,  1, -3,  2,  0])

我尝试过:

i = a[::-1].argsort().argsort()  # BAD attempt to store original index
# i = array([3, 5, 0, 4, 1, 2])

a[::-1].sort()  # in-place reverse sort (works correctly)
# a= array([ 2,  1,  0, -1, -2, -3])

a = a[i]  # FAILS to restore original a
# a = array([-1, -3,  2, -2,  1,  0])

以上操作无效.什么是正确的i可行?请假定数组很大,所以我们不想制作任何不必要的副本.

The above doesn't work. What would be the correct i that would work? Please assume the array is very large, so we don't want to make any unnecessary copies.

推荐答案

以下成语(O(n))比第二个argsort(O(n log n))便宜.

The following idiom is cheaper (O(n)) than the second argsort (O(n log n)).

具有排序顺序y

>>> x = np.random.random(10)
>>> y = x.argsort()[::-1]

建立逆向i

>>> i = np.empty_like(y)
>>> i[y] = np.arange(y.size)

检查:

>>> x
array([0.44257134, 0.573158  , 0.07762422, 0.31507426, 0.43414726,
       0.34923861, 0.22161337, 0.14090133, 0.66903264, 0.38888105])
>>> x[y]
array([0.66903264, 0.573158  , 0.44257134, 0.43414726, 0.38888105,
       0.34923861, 0.31507426, 0.22161337, 0.14090133, 0.07762422])
>>> x[y][i]
array([0.44257134, 0.573158  , 0.07762422, 0.31507426, 0.43414726,
       0.34923861, 0.22161337, 0.14090133, 0.66903264, 0.38888105])

这篇关于NumPy:取消/取消反向/降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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