如何交换矩阵的列,numpy

时间:2014-04-03 17:02:06

标签: python arrays numpy

您需要按对角线元素的衰减值对列进行排序,    0.884> 0.749> 0.640,    这个交换1和3列

numpy.array(
    [
        [ 0.640 -0.655  0.399]
        [ 0.617  0.749  0.239]
        [-0.456  0.093  0.884]
     ]

收到结果:

numpy.array(
    [
        [ 0.399 -0.655  0.640]
        [ 0.239  0.749  0.617]
        [-0.884  0.093 -0.456]
     ]

3 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西:

>>> a
array([[ 0.64 , -0.655,  0.399],
       [ 0.617,  0.749,  0.239],
       [-0.456,  0.093,  0.884]])
>>> a[:, np.argsort(a.diagonal() * -1)]
array([[ 0.399, -0.655,  0.64 ],
       [ 0.239,  0.749,  0.617],
       [ 0.884,  0.093, -0.456]])

答案 1 :(得分:1)

我愿意:

a[: , numpy.argsort(a.diagonal())[::-1] ]
  • a.diagonal获取[::-1]的对角线值,使其按相反顺序排列
  • numpy.argsort获取列的新订单

答案 2 :(得分:0)

您可以使用高级splicing

>>> import numpy as np
>>> a = np.arange(25).reshape(5,5)
>>> a
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])
>>> a[:,[0,4]] = a[:,[4,0]]
>>> a
array([[ 4,  1,  2,  3,  0],
       [ 9,  6,  7,  8,  5],
       [14, 11, 12, 13, 10],
       [19, 16, 17, 18, 15],
       [24, 21, 22, 23, 20]])
>>>