Python Numpy-如何按降序对值/键对数组进行排序
我正在研究这个问题,并提出了以下解决方案,但还有两个问题:Python Numpy-如何按降序对值/键对数组进行排序,python,arrays,numpy,Python,Arrays,Numpy,我正在研究这个问题,并提出了以下解决方案,但还有两个问题: 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([
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?
您可以将res和密钥合并到结构化数组中:
import numpy.lib.recfunctions as recfunctions
items = recfunctions.merge_arrays([res,keys])
由于np.sort没有reverse=True标志,因此我认为最好的方法是反转返回的数组,例如items[:-1],否则取res的负数:
屈服
[(-330.0, 'key3') (-230.0, 'key2') (-130.0, 'key1')]
[['key3']
['key2']
['key1']]
[ 330. 230. 130.]
请注意,refunctions.merge_数组只是一个Python便利函数。它使用zip和np.fromiter。避免将res和key合并,而是使用argsort查找对res进行排序的索引并使用这些索引对key进行重新排序肯定会更快:
屈服
[(-330.0, 'key3') (-230.0, 'key2') (-130.0, 'key1')]
[['key3']
['key2']
['key1']]
[ 330. 230. 130.]
可以使用numpy数组的argsort方法对键进行排序,索引将对其他数组进行排序
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]]
感谢@ondro和@unutbu,我终于得到了以下结果:
import numpy as np
# set up values
keys = np.array(['key1', 'key2', 'key3'])
values = np.array([
[1.1, 1.2, 1.3, 1.4], # values1_x
[2.1, 2.2, 2.3, 2.4], # values2_x
[3.1, 3.2, 3.3, 3.4] # values3_x
])
weights = np.array([10., 20., 30., 40.])
# crunch the numbers
res = np.dot(values, -weights) # negative of weights!
order = res.argsort(axis=0) # sorting on negative value gives
# same order as reverse-sort; there does
# not seem to be any way to reverse-sort
# directly
sortedkeys = keys[order].tolist()
它返回['key3'、'key2'、'key1']键,按值和权重的点积按相反顺序排序