简体   繁体   English

如何有效地排序一个numpy矩阵

[英]How to efficiently order a numpy matrix

I have this numpy array 我有这个numpy数组

matrix = np.array([[ 0.8,  0.2,  0.1],
   [ 1. ,  0. ,  0. ],
   [ 0. ,  0. ,  1. ]])

and I would like to filter to return, for each row of matrix the indices in decreasing value order. 而且我想过滤以matrix的每一行返回降序排列的索引。

For example, this would be 例如,这将是

np.array([[0, 1, 2], [0, 1, 2], [2, 0, 1]])

I know I could use np.argsort , but this doesn't seem to be returning the right output. 我知道我可以使用np.argsort ,但这似乎并没有返回正确的输出。 I tried changing the axis to different values, but that doesn't help either. 我尝试将axis更改为不同的值,但这也无济于事。

Probably the easiest way to get your desired output would be: 获得所需输出的最简单方法可能是:

(-matrix).argsort(axis=1)
# array([[0, 1, 2],
#        [0, 1, 2],
#        [2, 0, 1]])

I think np.argsort does seem to do the trick, you just need to make sure to flip the matrix horizontally to make it decreasing order: 我认为np.argsort确实可以解决问题,您只需要确保水平翻转矩阵以使其降序即可:

>>>matrix = np.array(
[[ 0.8,  0.2,  0.1],
[ 1. ,  0. ,  0. ],
[ 0. ,  0. ,  1. ]])

>>> np.fliplr(np.argsort(matrix))
array([[0, 1, 2],
       [0, 2, 1],
       [2, 1, 0]])

This should be the right output unless you have any requirements for sorting ties. 除非您对排序关系有任何要求,否则这应该是正确的输出。 Right now the flipping would make the rightmost tie the first index. 现在,翻转将使最右边的领带成为第一个索引。 If you wanted to match your exact output, where the leftmost index is first you could do a bit of juggling: 如果要匹配您的确切输出,则最左边的索引首先在此处,您可以做些杂耍:

# Flip the array first and get the indices
>>> flipped = np.argsort(np.fliplr(matrix))

# Subtract the width of your array to reverse the indices
# Flip the array to be in descending order
>>> np.fliplr(abs(flipped - flipped.shape[1]))
array([[0, 1, 2],
       [0, 1, 2],
       [2, 0, 1]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM