当我们有一个1D numpy数组时,我们可以按以下方式对其进行排序:
>>> temp = np.random.randint(1,10, 10)
>>> temp
array([5, 1, 1, 9, 5, 2, 8, 7, 3, 9])
>>> sort_inds = np.argsort(temp)
>>> sort_inds
array([1, 2, 5, 8, 0, 4, 7, 6, 3, 9], dtype=int64)
>>> temp[sort_inds]
array([1, 1, 2, 3, 5, 5, 7, 8, 9, 9])
注意:我知道我可以使用np.sort
;显然,我需要不同数组的排序索引-这只是一个简单的例子。现在我们可以继续我的实际问题。。在
我试图对二维阵列应用相同的方法:
^{pr2}$这个结果看起来不错——注意,我们可以使用sort_inds
中相应行的索引对d
的每一行进行排序,如1D示例所示。但是,尝试使用1D示例中使用的相同方法获取排序数组时,出现以下异常:
>>> d[sort_inds]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-63-e480a9fb309c> in <module>
----> 1 d[ind]
IndexError: index 5 is out of bounds for axis 0 with size 5
所以我有两个问题:
sort_inds
排序d
或任何其他相同维度的数组?在谢谢
您需要一些额外的工作来正确索引2d数组。下面是一种使用advanced indexing的方法,其中^{} 用于第一个轴,以便
sort_inds
中的每一行从d
中的相应行提取值:相关问题 更多 >
编程相关推荐