[英]numpy: applying argsort to an array
The argsort()
function returns a matrix of indices that can be used to index the original array so that the result would match the sort()
result. argsort()
函数返回索引矩阵,可用于索引原始数组,以便结果与sort()
结果匹配。
Is there a way to apply those indices? 有没有办法应用这些指数? I have two arrays, one is the array used for obtaining the sort order, and another is some associated data. 我有两个数组,一个是用于获取排序顺序的数组,另一个是一些关联数据。
I would like to compute assoc_data[array1.argsort()]
but that doesn't seem to work. 我想计算assoc_data[array1.argsort()]
但这似乎不起作用。
Here's an example: 这是一个例子:
z=array([1,2,3,4,5,6,7])
z2=array([z,z*z-7])
i=z2.argsort()
z2=array([[ 1, 2, 3, 4, 5, 6, 7],
[-6, -3, 2, 9, 18, 29, 42]])
i =array([[1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1]])
I would like to apply i to z2 (or another array with associated data) but I'm not sure how to do so. 我想将i应用于z2(或其他具有相关数据的数组),但我不知道该怎么做。
This is probably overkill, but this will work in the nd case: 这可能是矫枉过正,但这将适用于nd案例:
import numpy as np
axis = 0
index = list(np.ix_(*[np.arange(i) for i in z2.shape]))
index[axis] = z2.argsort(axis)
z2[index]
# Or if you only need the 3d case you can use np.ogrid.
axis = 0
index = np.ogrid[:z2.shape[0], :z2.shape[1], :z2.shape[2]]
index[axis] = z2.argsort(axis)
z2[index]
You're lucky I just got my masters degree in numpyology. 你很幸运我刚获得了numpyology的硕士学位。
>>> def apply_argsort(a, axis=-1):
... i = list(np.ogrid[[slice(x) for x in a.shape]])
... i[axis] = a.argsort(axis)
... return a[i]
...
>>> a = np.array([[1,2,3,4,5,6,7],[-6,-3,2,9,18,29,42]])
>>> apply_argsort(a,0)
array([[-6, -3, 2, 4, 5, 6, 7],
[ 1, 2, 3, 9, 18, 29, 42]])
For an explanation of what's going on, see my answer to this question . 有关正在发生的事情的解释,请参阅我对此问题的回答 。
Use np.take_along_axis
使用np.take_along_axis
np.take_along_axis(z2, i, axis=1)
Out[31]:
array([[ 1, 2, 3, 4, 5, 6, 7],
[-6, -3, 2, 9, 18, 29, 42]])
Aha, figured it out. 啊哈,想通了。
In [274]: z2[i,range(z2.shape[1])]
Out[274]:
array([[-6, -3, 2, 4, 5, 6, 7],
[ 1, 2, 3, 9, 18, 29, 42]])
I had this problem recently (using a.argsort(axis=something)
to sort b
). 我最近遇到了这个问题(使用a.argsort(axis=something)
来排序b
)。 Here is my implementation, with no lists if one cannot afford the run time: 这是我的实现,没有列表,如果一个人无法负担运行时间:
#For the example
import numpy as np
shape=(2,2,3,2)
t=np.random.randint(10,size=np.array(shape).prod()).reshape(shape)
#The axis to sort by
sortby=-1
#The actual sorting
x=t.swapaxes(sortby,-1) #I actually only know to do the final dimension, so I cheat
a=np.argsort(x,axis=-1)
p = np.array(x.shape[:-1]).prod()
x.T[a.T].T.reshape(p**2,x.shape[-1])[::p+1].reshape(x.shape).swapaxes(sortby,-1)
I am not sure why this works, but it seems to work for any dimensions and sorting axis. 我不知道为什么会这样,但它似乎适用于任何尺寸和排序轴。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.