以不同顺序对多列上的结构化numpy数组进行排序 [英] Sort Structured Numpy Array On Multiple Columns In Different Order

查看:285
本文介绍了以不同顺序对多列上的结构化numpy数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构化的numpy数组:

I have a structured numpy array:

dtype = [('price', float), ('counter', int)]
values = [(35, 1), (36, 2),
          (36, 3)]
a = np.array(values, dtype=dtype)

如果价格相等,我想对价格进行排序,然后对计数器进行排序:

I want to sort for price and then for counter if price is equal:

a_sorted = np.sort(a, order=['price', 'counter'])[::-1]

我需要按降序排列价格,当价格相等时,请考虑按升序排列.在上面的示例中,价格和计数器均按降序排列.

I need the price in a descending order and when prices are equal consider counter in ASCENDING order. In the example above both the price and the counter are in descending order.

我得到的是:

a_sorted: [(36., 3), (36., 2), (35., 1)]

我需要的是:

 a_sorted: [(36., 2), (36., 3), (35., 1)]

推荐答案

您可以使用 np.lexsort :

You can use np.lexsort:

a_sorted = a[np.lexsort((a['counter'], -a['price']))]

结果:

array([(36.0, 2), (36.0, 3), (35.0, 1)], 
      dtype=[('price', '<f8'), ('counter', '<i4')])

请记住,顺序是相反的,即首先由-a['price']执行排序.否定会照顾下降"方面.

Just remember the order is reversed, i.e. sorting is performed first by -a['price']. Negation takes care of the "descending" aspect.

这篇关于以不同顺序对多列上的结构化numpy数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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