问题
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