Question

If I have a 2D list in python, I can easily sort by the median value of each sublist like this:

import numpy as np
a = [[1,2,3],[1,1,1],[3,3,3,]]
a.sort(key=lambda x: np.median(x))
print a

Yielding...

[[1, 1, 1], [1, 2, 3], [3, 3, 3]]

Is there a way to do this with a numpy array without converting it to a regular python list?

a = np.array([[1,2,3],[1,1,1],[3,3,3,]])
a.sort(key=lambda x: np.median(x))
Was it helpful?

Solution

I guess the numpythonic way would be to use fancy-indexing:

>>> a = np.array([[1,2,3],[1,1,1],[3,3,3,]])
>>> a[np.median(a,axis=1).argsort()]
array([[1, 1, 1],
       [1, 2, 3],
       [3, 3, 3]])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top