本文介绍了numpy-如何按降序对值/键对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在查看问题最快的方法对具有多个值和权重的项目进行排名,并提出了以下解决方案,但还有两个问题:
I was looking at the problem Fastest way to rank items with multiple values and weightings and came up with the following solution, but with two remaining issues:
import numpy as np
# set up values
keys = np.array([
['key1'],
['key2'],
['key3']
])
values = np.matrix([
[1.1, 1.2, 1.3, 1.4],
[2.1, 2.2, 2.3, 2.4],
[3.1, 3.2, 3.3, 3.4]
])
weights = np.matrix([10., 20., 30., 40.]).transpose()
# crunch the numbers
res = values * weights
# combine results with labels
items = np.hstack((np.array(res), keys))
# !First problem - .hstack has promoted the first column from float64 to S4:
# array([['130.', 'key1'],
# ['230.', 'key2'],
# ['330.', 'key3']],
# dtype='|S4')
# How can I force it to stay numeric?
items.sort(reverse=True) # doesn't work, no 'reverse' argument
# !Second problem - how to sort the array in descending order?
推荐答案
您可以使用numpy数组的argsort
方法对具有对其他数组进行排序的索引的键进行排序.
You can use argsort
method of numpy arrays to sort keys with indices that would sort other array.
import numpy as np
# set up values
keys = np.array([
['key1'],
['key2'],
['key3']
])
values = np.array([
[1.1, 1.2, 1.3, 1.4],
[2.1, 2.2, 2.3, 2.4],
[3.1, 3.2, 3.3, 3.4]
])
weights = np.array([10., 20., 30., 40.])
# crunch the numbers
res = np.dot(values, weights)
sortedkeys = keys[res.argsort(axis=0)[::-1]]
这篇关于numpy-如何按降序对值/键对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!