Edwige Pezzulli Edwige Pezzulli - 1 month ago 21
Python Question

How to sort rows of a matrix by decreasing values of the first column in Python and numpy?

I have a matrix with

N = 250000
rows and
M = 10
columns.
I want to sort the matrix for decreasing values of the first column,
so I write:

matrix=np.loadtxt("matrix.dat")

np.sort(matrix)

matrix=matrix[::-1]


But the
np.sort
does not work. In fact, once printing the values after sorting, I find the same input matrix.
Anyone knows how to resolve this problem?
Thank you very much

Answer

This will sort a matrix for decreasing values of the first column

import numpy as np

# Generate a matrix of data
matrix = np.random.rand(5,4)

# Find the ordering of the first column (in increasing order)
ind = np.argsort(matrix[:,0])

# Switch the ordering (so it's decreasing order)
rind = ind[::-1]

# Return the matrix with rows in the specified order
matrix = matrix[rind]