Numpy: sort by key function Numpy: sort by key function numpy numpy

Numpy: sort by key function


your approach is right, it is similar to the Schwartzian transform or Decorate-Sort-Undecorate (DSU) idiom

As I said you can use the numpy function np.argsort. It does the work of your order_to_index.


For a more explicit answer, suppose we have an array x and want to sort the rows according to some function func which takes a row of x and outputs a scalar.

x[np.apply_along_axis(func, axis=1, arr=x).argsort()]

For this example

c1, c2 = 4, 7x = np.array([    [0, 1],    [2, 3],    [4, -5]])x[np.apply_along_axis(lambda row: c1 * / c2 * row[1] + row[0], 1, x).argsort()]

Out:

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

In this case, np.apply_along_axis isn't even necessary.

x[(c1 / c2 * x[:,1] + x[:,0]).argsort()]

Out:

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