Sort Structured Numpy Array On Multiple Columns In Different Order

时光毁灭记忆、已成空白 提交于 2020-07-18 22:26:28

问题


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.

What I get is:

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

what I need is:

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

回答1:


You can use np.lexsort:

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

Result:

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

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



来源:https://stackoverflow.com/questions/52556903/sort-structured-numpy-array-on-multiple-columns-in-different-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!