简体   繁体   English

用两列对NumPy数组进行排序

[英]Sorting NumPy array with two columns

I have the following array, which contains X and Y coordinates: 我有以下数组,其中包含XY坐标:

arr = array([[ 1.,  3.],
             [ 6.,  6.],
             [ 3.,  0.],
             [ 2.,  5.],
             [ 0.,  3.],
             [ 3.,  3.],
             [ 0.,  6.]])

I would like to know how can I sort this array by first sorting X and after by sorting Y . 我想知道如何通过首先对X进行排序然后对Y进行排序来对该数组进行排序。

I would like something like this: 我想要这样的东西:

new_ arr = array([[ 0.,  3.],
                  [ 0.,  6.],
                  [ 1.,  3.],
                  [ 2.,  5.],
                  [ 3.,  0.],
                  [ 3.,  3.],
                  [ 6.,  6.]])

You can use the np lexort function, you can read more in here 您可以使用np lexort函数,可以在此处阅读更多内容

numpy.lexsort(keys, axis=-1) Perform an indirect sort using a sequence of keys. numpy.lexsort(keys,axis = -1)使用一系列键执行间接排序。

Given multiple sorting keys, which can be interpreted as columns in a spreadsheet, lexsort returns an array of integer indices that describes the sort order by multiple columns. 给定多个排序键(可以将其解释为电子表格中的列),lexsort返回一个整数索引数组,该数组描述了按多个列排序的顺序。 The last key in the sequence is used for the primary sort order, the second-to-last key for the secondary sort order, and so on. 序列中的最后一个键用于主排序顺序,倒数第二个键用于辅助排序顺序,依此类推。 The keys argument must be a sequence of objects that can be converted to arrays of the same shape. keys参数必须是可以转换为相同形状的数组的对象序列。 If a 2D array is provided for the keys argument, it's rows are interpreted as the sorting keys and sorting is according to the last row, second last row etc 如果为keys参数提供了2D数组,则将其行解释为排序键,并根据最后一行,倒数第二行等进行排序

import numpy as np
arr = np.array([[ 1.,  3.],
             [ 6.,  6.],
             [ 3.,  0.],
             [ 2.,  5.],
             [ 0.,  3.],
             [ 3.,  3.],
             [ 0.,  6.]])
ind = np.lexsort(np.transpose(arr)[::-1])

print (arr[ind])

>>>[[ 0.  3.]
 [ 0.  6.]
 [ 1.  3.]
 [ 2.  5.]
 [ 3.  0.]
 [ 3.  3.]
 [ 6.  6.]]

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

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