Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于一列对numpy数组排序,然后基于另一列对subsort排序的最佳方法?_Python_Arrays_Python 3.x_Numpy_Numpy Ndarray - Fatal编程技术网

Python 基于一列对numpy数组排序,然后基于另一列对subsort排序的最佳方法?

Python 基于一列对numpy数组排序,然后基于另一列对subsort排序的最佳方法?,python,arrays,python-3.x,numpy,numpy-ndarray,Python,Arrays,Python 3.x,Numpy,Numpy Ndarray,嗨,我相信这是一个最好的例子来说明的问题 我有一个numpy数组 array = [[ 101 27] [6 355] [6400 85] [ 33 96]] 我想根据第二列(升序)中的值对数组进行排序,以获得 然后我想按第一列升序排序,但只对第1行和第2行进行排序。然后重复第三行和第四行 最后一步可以用伪代码解释: if array[0][0] > array[1][0]: transpose array[0] and array[1] if array[2][0

嗨,我相信这是一个最好的例子来说明的问题

我有一个numpy数组

array =  
[[ 101  27]
 [6  355]
 [6400 85]
 [ 33 96]]
我想根据第二列(升序)中的值对数组进行排序,以获得

然后我想按第一列升序排序,但只对第1行和第2行进行排序。然后重复第三行和第四行

最后一步可以用伪代码解释:

if array[0][0] > array[1][0]:
    transpose array[0] and array[1]
if array[2][0] > array[3][0]:
    transpose array[2] and array[3]
这使得:

array =  
[[ 101  27]
[6400 85]
[6  355]
[ 33 96]]

我可以很容易地做到这一点,但代码不是很好,我假设有一种优雅/高效的方法来做到这一点?

您可以使用python中内置的
排序
函数轻松完成任务

试试这个:

array = sorted(array, key=lambda x: x[1])
array[:2] = sorted(array[:2], key=lambda x: x[0]) # sort first two rows by first col
array[2:] = sorted(array[2:], key=lambda x: x[0]) # sort next two rows by first col

print(array)
[[101, 27],
[6400, 85], 
[6, 355], 
[33, 96]]
输出:

array = sorted(array, key=lambda x: x[1])
array[:2] = sorted(array[:2], key=lambda x: x[0]) # sort first two rows by first col
array[2:] = sorted(array[2:], key=lambda x: x[0]) # sort next two rows by first col

print(array)
[[101, 27],
[6400, 85], 
[6, 355], 
[33, 96]]