简体   繁体   English

排序非整数2D numpy数组

[英]Sorting a non-integer 2D numpy array

how would you sort a 2d array with x and y coordinates that are non-integers and are approximate? 如何将x和y坐标为非整数且近似的2d数组排序? So, for example such an array as: 因此,例如这样的数组:

[
[0.005, 0.02]
[-0.1, 1.001]
[0.99, 0.004]
[1.1, 0.995]
]

Keep in mind that the [0.005, 0.02] corresponding to the x,y coordinate of [0,0] does not necessarily have the lowest x coordinate or the lowest y coordinate. 请记住,与[0,0]的x,y坐标对应的[0.005,0.02]不一定具有最低的x坐标或最低的y坐标。 I have seen how to do it for integers, but I am not sure for this case. 我已经看到了如何对整数进行操作,但是对于这种情况我不确定。

As Sven pointed out, you need a comparison. 正如Sven指出的,您需要进行比较。 If you are sorting by distance, then you need to compute at least the square. 如果按距离排序,则至少需要计算平方。 You can use this: 您可以使用此:

x = np.array([[1,2],[0.1,0.2],[-1,0.5], [2,2], [0,0]])
x[np.multiply(x,x).sum(axis=1).argsort()]

If you want to sort by x or y, you can use argsort on a slice: 如果要按x或y排序,可以在切片上使用argsort:

x[x[:,0].argsort()] # sort by x
x[x[:,1].argsort()] # sort by y

You have an (N,2) array of floats. 您有(N,2)个浮点数组。 I made a dummy array similar to yours: 我做了一个类似于你的虚拟数组:

>>import numpy as np
>>A = np.random.random((5,2))*3 - 1 
>>A

array([[-0.09759485,  1.09646624],
       [ 1.24045241,  0.59099876],
       [-0.43080349, -0.33879412],
       [ 0.82403019,  0.16274243],
       [ 1.95623418, -0.64082276]])

From what you said, these values are approximate. 从您所说的来看,这些值是近似值。 Before ordering them we can round them to the nearest integers. 在订购它们之前,我们可以将它们四舍五入到最接近的整数。

>>A = np.round(A)
>>A
array([[-0.,  1.],
       [ 1.,  1.],
       [-0., -0.],
       [ 1.,  0.],
       [ 2., -1.]])

Now numpy.sort() should give you the array ordered how you wanted: 现在, numpy.sort()应该给您按需要排序的数组:

>>np.sort(A, axis=0)
>>A
array([[-0., -1.],
       [-0., -0.],
       [ 1.,  0.],
       [ 1.,  1.],
       [ 2.,  1.]])

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

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