简体   繁体   English

有效地排列numpy矩阵行

[英]Sort rows of numpy matrix efficiently

I have a numpy 2d array of real numbers, for example 例如,我有一个numpy 2d数组的实数

A=
np.array(
[[0.1, 0.01, 0.4, 0.9], 
[0.0005, -0.2, -0.1, 0.6], 
[-0.3, -0.5, 0.2, 0.9]])

and a vector of indices of the same size of A.shape[1] : idx=[5, 2, 3, 9] A.shape[1]相同大小的索引向量: idx=[5, 2, 3, 9] A.shape[1] idx=[5, 2, 3, 9]

for every row of A, I need to sort the entries from high to low, and provide the corresponding elements from idx. 对于A的每一行,我需要将条目从高到低排序,并提供来自idx的相应元素。 For example, in the case above the answer should be: 例如,在上面的情况下,答案应该是:

np.array([[9, 3, 5, 2], [9, 5, 3, 2], [9, 3, 5, 2]])

There can be millions of row in A. What is the most efficient way of doing this? A中可能有数百万行。最有效的方法是什么?

You can use np.argsort() to get the indices of your array in a sorted mode and reverse it to get the indices of decreasing mode, then use a simple indexing to get your expected output: 您可以使用np.argsort()以排序模式获取数组的索引并将其反转以获得减少模式的索引,然后使用简单的索引来获得预期的输出:

>>> A.argsort()
array([[1, 0, 2, 3],
       [1, 2, 0, 3],
       [1, 0, 2, 3]])
>>> idx=np.array([5, 2, 3, 9])

>>> indices = A.argsort()[:,::-1]
>>> 
>>> idx[indices]
array([[9, 3, 5, 2],
       [9, 5, 3, 2],
       [9, 3, 5, 2]])

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

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