Skip to content Skip to sidebar Skip to footer

Sort A Numpy Python Matrix Progressively According To Rows

I have searched around and tried to find a solution to what seems to be a simple problem, but have come up with nothing. The problem is to sort a matrix based on its columns, progr

Solution 1:

It's not going to be particularly fast, but you can always convert your rows to tuples, then use Python's sort:

np.matrix(sorted(map(tuple, X.A)))

You can also use np.lexsort, as suggested in this answer to a somewhat related question:

X[np.lexsort(X.T[::-1])]

The lexsort approach appears to be faster, though you should test with your actual data to make sure:

In [20]: X = np.matrix(np.random.randint(10, size=(100,100)))

In [21]: %timeit np.matrix(sorted(map(tuple, X.A)))
100 loops, best of 3: 2.23 ms per loop

In [22]: %timeit X[np.lexsort(X.T[::-1])]
1000 loops, best of 3: 1.22 ms per loop

Solution 2:

Here:

data = [[0,0,1,2],[0,0,1,1],[0,0,0,4],[0,0,0,3],[0,1,2,5]]
x  = pandas.DataFrame(data)
# order of columns to sortz = x.sort([0,1,2,3])
output = z.as_matrix()

output:

array([[0, 0, 0, 3],
   [0, 0, 0, 4],
   [0, 0, 1, 1],
   [0, 0, 1, 2],
   [0, 1, 2, 5]])

Post a Comment for "Sort A Numpy Python Matrix Progressively According To Rows"