Skip to main content
 首页 » 编程设计

python之如何使用特定的列索引对 numpy 二维数组行进行降序或升序排序

2024年10月17日9shanyou

假设我有一个像这样的 numpy 二维数组:

a = np.array([[3,6,7],[1,9,4],[ 3,7,8],[2,5,10]]) 
a 
# array([[ 3,  6,  7], 
#       [ 1,  9,  4], 
#       [ 3,  7,  8], 
#       [ 2,  5, 10]]) 

我需要根据第一列降序排列并根据第二列升序排列行以获得以下结果:

array([[ 3,  6,  7], 
       [ 3,  7,  8], 
       [ 2,  5,  10], 
       [ 1,  9, 4]]) 

在 Matlab 中使用 sortrows(my_matrix,[-1 2]) 很简单,其中 -1 表示第一列降序,2 表示第二列升序。

不知道numpy中有没有这样的函数

请您参考如下方法:

以下是使用 numpy_indexed 的方法包裹:

import numpy_indexed as npi 
print(a[npi.argsort((a[:,1], -a[:,0]))])