我有一个结构化的 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)]
最佳答案
您可以使用 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']
执行。否定处理“下降”方面。
关于python - 以不同顺序对多个列上的结构化 Numpy 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52556903/