【问题标题】:Sorting an array along its last dimension, and undoing the sorting沿其最后一维对数组进行排序,并撤消排序
【发布时间】:2021-05-19 21:35:03
【问题描述】:

在我当前的项目中,我有一个 D 维数组。为了说明起见,我们可以假设 D=2,但是代码应该在任意高的维度上工作。当它根据最后一个维度排序时,我需要对这个矩阵运行一些操作,然后在矩阵上反转排序。

矩阵排序的第一部分比较简单:

import numpy as np

D = 2
matrix = np.random.uniform(low=0.,high=1.,size=tuple([5]*D))
matrix_sorted = np.sort(matrix,axis=-1)

这段代码 sn-p 根据最后一个维度对矩阵进行排序,但不记得数组是如何排序的,因此不允许我恢复排序。或者,我可以使用以下行获取排序索引:

sorted_indices = np.argsort(matrix,axis=-1)

不幸的是,这些索引似乎不是很有用。我不确定如何使用这些排序索引来(a)对矩阵进行排序,以及(b)在一般 D 的情况下撤消排序。一种简单的方法是为 @ 的所有行创建一个 for 循环987654324@ case(在这种情况下,我们对列进行了排序),但由于我希望代码适用于任意维度,因此硬编码嵌套的 for 循环并不是一个真正的选择。

你对我如何解决这个问题有什么优雅的建议吗?

【问题讨论】:

  • 为什么不只存储两个列表......未排序的一个和排序的......
  • 因为我需要对排序后的数组做一些操作,撤消排序后应该会持续存在。不幸的是,这些操作需要对数组进行排序。
  • 然后在操作前存储排序好的数组......
  • 我不确定保存初始数组有什么帮助。想象一下:我有一个数组 [[3,2,1],[2,3,5]]。我想对其进行排序,所以我得到 [[1,2,3],[2,3,5]] (第一行颠倒,第二行保持不变)。然后我做一些复杂的操作,得到[[7,8,1],[5,6,2]]。现在我想恢复排序,所以目标应该是[[1,8,7],[5,6,2]]。我当然会存储初始数组,但这无助于撤消排序。
  • docs 提供了一个很好的例子,使用来自argsort() 的结果来获得排序矩阵 -- np.take_along_axis(matrix, sorted_indices, axis=-1)

标签: python arrays python-3.x numpy sorting


【解决方案1】:

所以是的,在遵循Mark M 的建议并阅读了从那里继续的其他一些 StackOverflow 答案之后,答案似乎如下:

import numpy as np

# Create the initial random matrix
D               = 2
matrix          = np.random.uniform(low=0.,high=1.,size=tuple([5]*D))

# Get the sorting indices
sorting         = np.argsort(matrix,axis=-1)

# Get the indices for unsorting the matrix
reverse_sorting = np.argsort(sorting,axis=-1)

# Sort the initial matrix
matrix_sorted   = np.take_along_axis(matrix, sorting, axis=-1)

# Undo the sorting
matrix_unsorted = np.take_along_axis(matrix_sorted, reverse_sorting, axis=-1)

这个技巧包括两个步骤:np.take_along_axis 允许我们根据从 np.argsort 获得的索引对任意维矩阵进行排序,并且对索引进行排序为我们提供了再次使用 @ 撤消排序所需的索引集987654325@。我可以在倒数第二步和最终步骤之间进行所需的复杂操作。完美!

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    相关资源
    最近更新 更多