简体   繁体   English

在 python 中按行对二维数组进行排序

[英]Sorting 2d array by rows in python

I would like to rearrange the rows in a python numpy array according to descending order of the first column.我想根据第一列的降序重新排列 python numpy 数组中的行。 For Example,例如,

([[2,3,1,8],
  [4,7,5,20],
  [0,-2,2,0]])

to be converted to转换为

([[0,-2,2,0],
  [2,3,1,8],
  [4,7,5,20]])

such that first column converts to [0,2,4] from [2,4,0]这样第一列从[2,4,0]转换为[0,2,4] ]

Regular sorted does it:常规sorted这样做:

print(sorted([[2,3,1,8], [4,7,5,20], [0,-2,2,0]]))

But if you only want to sort by the first columns, use:但是,如果您只想按第一列排序,请使用:

print(sorted([[2,3,1,8], [4,7,5,20], [0,-2,2,0]], key=lambda x: x[0]))

They both output:他们都是 output:

[[0, -2, 2, 0], [2, 3, 1, 8], [4, 7, 5, 20]]

If you intend to get numpy operation:如果您打算获得numpy操作:

arr = arr[arr[:,0].argsort()]

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

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