撤消或反向argsort(),python [英] undo or reverse argsort(), python

查看:124
本文介绍了撤消或反向argsort(),python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数组"a",我想按列对数组进行排序.sort(a, axis=0)对数组做一些处理,然后撤消排序.我所说的不是重新排序,而是基本上颠倒了每个元素的移动方式.我认为argsort()是我所需要的,但是我不清楚如何用argsort()的结果对数组进行排序,或更重要的是应用argsort()

Given an array 'a' I would like to sort the array by columns sort(a, axis=0) do some stuff to the array and then undo the sort. By that I don't mean re sort but basically reversing how each element was moved. I assume argsort() is what I need but it is not clear to me how to sort an array with the results of argsort() or more importantly apply the reverse/inverse of argsort()

这里有更多细节

我有一个数组ashape(a) = rXc我需要对每一列进行排序

I have an array a, shape(a) = rXc I need to sort each column

aargsort = a.argsort(axis=0)  # May use this later
aSort = a.sort(axis=0)

现在平均每一行

aSortRM = asort.mean(axis=1)

现在用行均值替换一行中的每个col. 有没有比这更好的方法

now replace each col in a row with the row mean. is there a better way than this

aWithMeans = ones_like(a)
for ind in range(r)  # r = number of rows
    aWithMeans[ind]* aSortRM[ind]

现在,我需要撤消在第一步中所做的排序. ????

Now I need to undo the sort I did in the first step. ????

推荐答案

我不确定如何在numpy中做到最好,但是,在纯Python中,推理将是:

I'm not sure how best to do it in numpy, but, in pure Python, the reasoning would be:

aargsort保留了range(len(a))的排列,告诉您aSort的项目来自何处-就像在纯Python中一样:

aargsort is holding a permutation of range(len(a)) telling you where the items of aSort came from -- much like, in pure Python:

>>> x = list('ciaobelu')
>>> r = range(len(x))
>>> r.sort(key=x.__getitem__)
>>> r
[2, 4, 0, 5, 1, 6, 3, 7]
>>> 

sorted(x)的第一个参数是x[2],第​​二个参数x[4],依此类推.

i.e., the first argument of sorted(x) will be x[2], the second one x[4], and so forth.

因此,给定排序的版本,您可以通过将项目放回它们的来源"来重建原始版本:

So given the sorted version, you can reconstruct the original by "putting items back where they came from":

>>> s = sorted(x)
>>> s
['a', 'b', 'c', 'e', 'i', 'l', 'o', 'u']
>>> original = [None] * len(s)
>>> for i, c in zip(r, s): original[i] = c
... 
>>> original
['c', 'i', 'a', 'o', 'b', 'e', 'l', 'u']
>>> 

当然,会有更严格,更快速的方法来用numpy表示(不幸的是,我对Python的了解不如我对Python本身的了解;-),但是我希望这可以通过显示您需要执行的将东西放回原位"操作的基本逻辑.

Of course there are going to be tighter and faster ways to express this in numpy (which unfortunately I don't know inside-out as much as I know Python itself;-), but I hope this helps by showing the underlying logic of the "putting things back in place" operation you need to perform.

这篇关于撤消或反向argsort(),python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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