numpy: applying argsort to an array
This is probably overkill, but this will work in the nd case:
import numpy as npaxis = 0index = list(np.ix_(*[np.arange(i) for i in z2.shape]))index[axis] = z2.argsort(axis)z2[index]# Or if you only need the 3d case you can use np.ogrid.axis = 0index = np.ogrid[:z2.shape[0], :z2.shape[1], :z2.shape[2]]index[axis] = z2.argsort(axis)z2[index]
You're lucky I just got my masters degree in numpyology.
>>> def apply_argsort(a, axis=-1):... i = list(np.ogrid[[slice(x) for x in a.shape]])... i[axis] = a.argsort(axis)... return a[i]... >>> a = np.array([[1,2,3,4,5,6,7],[-6,-3,2,9,18,29,42]])>>> apply_argsort(a,0)array([[-6, -3, 2, 4, 5, 6, 7], [ 1, 2, 3, 9, 18, 29, 42]])
For an explanation of what's going on, see my answer to this question.