Numpy: sort by key function

2019-04-08 23:08发布

问题:

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 to this function:

c1,c2= 4,7
lambda row: c1*(row[1]/c2)+row[0]

I realise one possible solution would be to generate a vector with the key value of each row, but how would one sort according to it? Should one seek to convert such vector into a index vector somehow?

order= c1*(matrix[:,1]/c2)+matrix[:,0]
indexes= order_to_index( order )
return matrix[ indexes ]

Is this realistic?

回答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.