8

我有一个矩阵,它应该在对角线上有一个,但列是混合的。

混乱的矩阵

但我不知道如何在没有明显的 for 循环的情况下有效地交换行以在对角线上获得统一。我什至不确定我会传递什么键来排序。

有什么建议么?

4

2 回答 2

7

您可以使用 numpyargmax来确定目标列排序,并使用 argmax 结果作为列索引重新排序矩阵:

>>> z = numpy.array([[ 0.1 ,  0.1 ,  1.  ],
...                  [ 1.  ,  0.1 ,  0.09],
...                  [ 0.1 ,  1.  ,  0.2 ]])

numpy.argmax(z, axis=1)

>>> array([2, 0, 1]) #Goal column indices

z[:,numpy.argmax(z, axis=1)]

>>> array([[ 1.  ,  0.1 ,  0.1 ],
...        [ 0.09,  1.  ,  0.1 ],
...        [ 0.2 ,  0.1 ,  1.  ]])
于 2012-08-22T02:56:00.333 回答
3
>>> import numpy as np
>>> a = np.array([[ 1. ,  0.5,  0.5,  0. ],
...               [ 0.5,  0.5,  1. ,  0. ],
...               [ 0. ,  1. ,  0. ,  0.5],
...               [ 0. ,  0.5,  0.5,  1. ]])
>>> np.array(sorted(a, cmp=lambda x, y: list(x).index(1) - list(y).index(1)))
array([[ 1. ,  0.5,  0.5,  0. ],
       [ 0. ,  1. ,  0. ,  0.5],
       [ 0.5,  0.5,  1. ,  0. ],
       [ 0. ,  0.5,  0.5,  1. ]])

它实际上按行排序,而不是按列排序(但结果是相同的)。它通过按所在列的索引进行排序来工作1

于 2012-08-22T02:47:59.667 回答