【问题标题】:Sort numpy matrix based on index-matrix根据索引矩阵对 numpy 矩阵进行排序
【发布时间】:2021-06-29 04:38:15
【问题描述】:

在 numpy 中,我们可以像这样对数组进行排序:

>>> import numpy as np

>>> a = np.array([0, 100, 200])
>>> order = np.array([1, 2, 0])
>>> print(a[order])
[100 200   0]

但是,当“订单”是矩阵时,这不起作用:

>>> A = np.array([    [0, 1, 2],
                      [3, 4, 5],
                      [6, 7, 8]])

>>> Ord = np.array([  [1, 0, 2],
                      [0, 2, 1],
                      [2, 1, 0]])

>>> print(A[Ord].shape)
(3, 3, 3)

我希望“A”这样排序:

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

【问题讨论】:

    标签: python arrays numpy sorting matrix


    【解决方案1】:

    您可以为此使用np.take_along_axis

    np.take_along_axis(A, Ord, axis=1)
    

    输出

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

    如文档中所述,它通常与生成索引的函数一起使用,例如argsort。但我不确定这是否会推广到超过 2 个维度。

    【讨论】:

      【解决方案2】:

      索引到numpy 数组的一般方法有两种:

      1. 基本的索引和切片扩展了 python 的切片概念。
      2. 高级索引,我们通常使用另一个包含整数/布尔值的 ndarray。

      您可以在numpy documentation 中了解这些内容。

      回答您的问题:我们可以在此处使用高级索引。文档包含一个示例,改编如下,它已经非常接近我们想要的:

      >>> import numpy as np
      >>> A = np.array([[1,2],
                        [3,4]])
      >>> row_indices = np.array([[0,0],
                                  [1,1]])
      >>> col_indices = np.array([[1,0],
                                  [1,0]])
      >>> A[row_indices,col_indices]
      array([[2, 1],
             [4, 3]])
      

      在问题的代码中,Ord 已经包含列索引,所以我们需要做的就是自己生成行索引。虽然这可能不是最好的方法,但这是一种可能的解决方案:

      >>> A = np.array( [[0,1,2],
      ...                [3,4,5],
      ...                [6,7,8]])
      >>> col_indices = np.array([[1,0,2],
      ...                         [0,2,1],
      ...                         [2,1,0]])
      >>> row_indices = np.repeat([0,1,2],3).reshape(3,3)
      >>> row_indices
      array([[0, 0, 0],
             [1, 1, 1],
             [2, 2, 2]])
      >>> A[row_indices, col_indices]
      array([[1, 0, 2],
             [3, 5, 4],
             [8, 7, 6]])
      

      【讨论】:

        猜你喜欢
        • 2012-08-17
        • 2020-11-04
        • 2016-04-18
        • 1970-01-01
        • 2019-05-13
        • 2018-04-09
        • 2019-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多