使用返回的索引对2D numpy数组排序np.argsort公司()

2024-10-01 07:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当我们有一个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

所以我有两个问题:

  1. 刚才发生什么事了?纽比是如何解释这段代码的?在
  2. 我如何仍然可以实现我想要的结果——也就是说,使用sort_inds排序d或任何其他相同维度的数组?在

谢谢


Tags: 方法numpy示例排序np方式random数组
1条回答
网友
1楼 · 发布于 2024-10-01 07:24:47

您需要一些额外的工作来正确索引2d数组。下面是一种使用advanced indexing的方法,其中^{}用于第一个轴,以便sort_inds中的每一行从d中的相应行提取值:

d[np.arange(d.shape[0])[:,None], sort_inds]

array([[1, 1, 2, 3, 3, 4, 4, 7, 8, 9],
       [1, 3, 4, 5, 5, 5, 6, 8, 8, 9],
       [1, 2, 3, 4, 5, 6, 7, 8, 8, 8],
       [2, 2, 4, 7, 7, 8, 8, 9, 9, 9],
       [1, 1, 2, 4, 4, 7, 7, 8, 8, 8]])

相关问题 更多 >