Skip to content Skip to sidebar Skip to footer

Numpy: Sort By Key Function

Is there a way to sort the rows of a numpy ndarray using a key (or comparator) function, without resorting to converting to a python list? In particular, I need to sort according

Solution 1:

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.

Solution 2:

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, 7
x = 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]])

Post a Comment for "Numpy: Sort By Key Function"