根据对角线对numpy矩阵进行排序 [英] Sort a numpy matrix based on its diagonal

查看:141
本文介绍了根据对角线对numpy矩阵进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵,对角线上应该有一个矩阵,但各列混合在一起.

I have a matrix that should have ones on the diagonal but the columns are mixed up.

但是我不知道如何在没有明显的for循环的情况下有效地交换行以使对角线统一.我什至不知道我该传递什么样的密钥.

But I don't know how, without the obvious for loop, to efficiently interchange rows to get unity on the diagonals. I'm not even sure what key I would pass to sort on.

有什么建议吗?

推荐答案

您可以使用numpy的

You can use numpy's argmax to determine the goal column ordering and reorder your matrix using the argmax results as column indices:

>>> 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.  ]])

这篇关于根据对角线对numpy矩阵进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆