Sorting arrays in NumPy by column

后端 未结 13 2222
既然无缘
既然无缘 2020-11-22 03:47

How can I sort an array in NumPy by the nth column?

For example,

a = array([[9, 2, 3],
           [4, 5, 6],
           [7, 0, 5]])

13条回答
  •  醉酒成梦
    2020-11-22 04:14

    I had a similar problem.

    My Problem:

    I want to calculate an SVD and need to sort my eigenvalues in descending order. But I want to keep the mapping between eigenvalues and eigenvectors. My eigenvalues were in the first row and the corresponding eigenvector below it in the same column.

    So I want to sort a two-dimensional array column-wise by the first row in descending order.

    My Solution

    a = a[::, a[0,].argsort()[::-1]]
    

    So how does this work?

    a[0,] is just the first row I want to sort by.

    Now I use argsort to get the order of indices.

    I use [::-1] because I need descending order.

    Lastly I use a[::, ...] to get a view with the columns in the right order.

提交回复
热议问题