[英]Problems sorting an 2D array
I have a following 2D numpy array: 我有以下2D numpy数组:
array([[1 0]
[2 0]
[4 0]
[1 1]
[2 1]
[3 1]
[4 2])
I want to sort the ID of first column with its value in second value, suck that I get back: 我想用第二个值对第一列的ID进行排序,这很糟糕:
array([[1 0]
[1 1]
[2 0]
[2 1]
[3 1]
[4 0]
[4 2]])
I am getting O(n^2) complexity and want to improve it further. 我正在获得O(n ^ 2)复杂度,并希望进一步提高它。
Try the below code, Hope this will help: 请尝试以下代码,希望对您有所帮助:
a = np.array([[1, 0],
[2 ,0],
[4 ,0],
[1 ,1],
[2 ,1],
[3 ,1],
[4 ,2]])
np.sort(a.view('i8,i8'), order=['f0'], axis=0).view(np.int)
Ouput will be : Ouput将是:
array([[(1, 0)],
[(1, 1)],
[(2, 0)],
[(2, 1)],
[(3, 1)],
[(4, 0)],
[(4, 2)]])
A better way to sort a list of lists: 一种更好的列表列表排序方法:
import numpy as np
a = np.array([[1, 0], [2 ,0], [4 ,0], [1 ,1], [2 ,1], [3 ,1], [4 ,2]])
s_a = np.asarray(sorted(a, key=lambda x: x[0]))
print(s_a)
Output: 输出:
[[1 0]
[1 1]
[2 0]
[2 1]
[3 1]
[4 0]
[4 2]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.