Numpy:按键功能排序 [英] Numpy: sort by key function

查看:123
本文介绍了Numpy:按键功能排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使用键(或比较器)函数对numpy ndarray的行进行排序,而无需转换为python列表?



特别是,我需要根据这个函数进行排序:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆