重新排序numpy中的矩阵

问题描述 投票:0回答:1

假设我有一个3x3的任意矩阵,其中

           A  B  C
       A [[0, 1, 0],
       B [1, 0, 1],
       C [0, 1, 0]]

而且我有一个列表labels = [0,1,0]对应于矩阵的每一列。例如,0对应于列1,1对应于列2,依此类推。我想对矩阵重新排序,以便按标签的升序对其进行排序。

第1列是A,第2列是B,第3列是C。第1行是A,第2行是B,第3行是C。该顺序不应弄乱每行/列的含义。

所以我期望的矩阵输出矩阵将是:

          C  A  B
      C [[0, 0, 1],
      A [0, 0, 1],
      B [1, 1, 0]]
python pandas numpy
1个回答
0
投票

这花了我一些时间来理解,但我想我知道您现在想做什么。

>>> x = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])
>>> labels = [0, 1, 0]
>>> order = np.argsort(labels) # Find a sorted order of the given labels
>>> x[order][:, order] # Sort the rows and then the columns
array([[0, 0, 1],
       [0, 0, 1],
       [1, 1, 0]])
© www.soinside.com 2019 - 2024. All rights reserved.