按不同顺序在多个列上对结构化的Numpy数组进行排序

4

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

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

我想按价格排序,如果价格相等,则按柜台排序:
a_sorted = np.sort(a, order=['price', 'counter'])[::-1]

我需要按价格降序排列,如果价格相同,则按计数器升序排列。在上面的示例中,价格和计数器都是按降序排列的。

我得到的结果是:

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

我需要的是:

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

4

你可以使用 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']排序。否定处理了“降序”的方面。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接