Jas*_*n S 7 python arrays numpy
该argsort()函数返回一个索引矩阵,可用于索引原始数组,以便结果与sort()结果匹配.
有没有办法应用这些指数?我有两个数组,一个是用于获取排序顺序的数组,另一个是一些关联数据.
我想计算,assoc_data[array1.argsort()]但似乎不起作用.
这是一个例子:
z=array([1,2,3,4,5,6,7])
z2=array([z,z*z-7])
i=z2.argsort()
Run Code Online (Sandbox Code Playgroud)
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]])
Run Code Online (Sandbox Code Playgroud)
我想将i应用于z2(或其他具有相关数据的数组),但我不知道该怎么做.
这可能是矫枉过正,但这将适用于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]
Run Code Online (Sandbox Code Playgroud)
你很幸运,我刚刚获得了麻痹学硕士学位。
>>> 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]])
Run Code Online (Sandbox Code Playgroud)
有关正在发生的事情的解释,请参阅我对这个问题的回答。
| 归档时间: |
|
| 查看次数: |
7159 次 |
| 最近记录: |