【发布时间】:2018-04-13 04:14:07
【问题描述】:
numpy.argsort 文档状态
返回:
index_array :ndarray,int 沿指定轴对 a 进行排序的索引数组。如果 a 是一维的,a[index_array]会产生一个已排序的 a。
如何将numpy.argsort 的结果应用于多维数组以取回已排序的数组? (不仅仅是一维或二维数组;它可以是一个 N 维数组,其中 N 仅在运行时才知道)
>>> import numpy as np
>>> np.random.seed(123)
>>> A = np.random.randn(3,2)
>>> A
array([[-1.0856306 , 0.99734545],
[ 0.2829785 , -1.50629471],
[-0.57860025, 1.65143654]])
>>> i=np.argsort(A,axis=-1)
>>> A[i]
array([[[-1.0856306 , 0.99734545],
[ 0.2829785 , -1.50629471]],
[[ 0.2829785 , -1.50629471],
[-1.0856306 , 0.99734545]],
[[-1.0856306 , 0.99734545],
[ 0.2829785 , -1.50629471]]])
对我来说,这不仅仅是使用sort() 的问题;我有另一个数组B,我想使用np.argsort(A) 沿相应轴的结果订购B。考虑以下示例:
>>> A = np.array([[3,2,1],[4,0,6]])
>>> B = np.array([[3,1,4],[1,5,9]])
>>> i = np.argsort(A,axis=-1)
>>> BsortA = ???
# should result in [[4,1,3],[5,1,9]]
# so that corresponding elements of B and sort(A) stay together
【问题讨论】:
-
stackoverflow.com/questions/37878946/… 密切相关,但对于一般的 N 维情况,这个答案并不能帮助我回答这个问题
-
take_along_axis现在是numpy的一部分
标签: python arrays sorting numpy