Numpy:按键功能排序 [英] Numpy: sort by key function
问题描述
特别是,我需要根据这个函数进行排序:
c1,c2 = 4,7
lambda row:c1 *(row [1] / c2)+ row [0]
我意识到一个可能的解决方案是用每行的关键值生成一个向量,但是如何根据它来排序呢?是否应该试图将这种向量转换为索引向量?
order = c1 *(matrix [:,1] / c2 )+ matrix [:,0]
indexes = order_to_index(order)
return matrix [indexes]
这是否现实?
您的方法是正确的,它类似于 Schwartzian transform 或 Decorate-Sort-Undecorate(DSU)idiom 正如我所说的,你可以使用numpy函数 np.argsort 。它完成了 order_to_index
的工作。
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?
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
.
这篇关于Numpy:按键功能排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!