简体   繁体   English

如何在将二维 numpy 数组放入 python 中的 function 时根据它们的值对它们进行排序

[英]How to sort a 2d numpy array based on their value when put into a function in python

Let's say I have a NumPy array:假设我有一个 NumPy 数组:

[[7 2]
 [7 3]
 [2 8]
 [4 3]
 [5 5]] 

Where the 0th index is the x value and the 1st index is the y value.其中第 0 个索引是 x 值,第 1 个索引是 y 值。 How do I sort these values so that when I put them into the function: (x^2 + y- 11)^2 + (x + y^2 -7)^2 , they get sorted in ascending order depending on the results?如何对这些值进行排序,以便当我将它们放入 function: (x^2 + y- 11)^2 + (x + y^2 -7)^2时,它们会根据结果按升序排序? so the sorted values would look like this:所以排序后的值如下所示:

[[4 3]
 [5 5]
 [7 2]
 [7 3]
 [2 8]]

The arrays can have duplicates. arrays 可以有重复项。

One of my ideas would be to use the.argsort() method, though I don't know how I could implement that.我的一个想法是使用 .argsort() 方法,尽管我不知道如何实现它。

Thanks!谢谢!

You can apply the function you have along the first axis to get a one dimensional array with the function values.您可以沿第一个轴应用 function 以获得具有 function 值的一维数组。 Passing that result to np.argsort() will give you the proper sorting indices:将该结果传递给np.argsort()将为您提供正确的排序索引:

a = np.array([
     [7, 2],
     [7, 3],
     [2, 8],
     [4, 3],
     [5, 5]] 
)

def my_func(row):
    x, y = row
    return (x ** 2 + y - 11) ** 2 + (x + y ** 2) ** 2

f = np.apply_along_axis(my_func, 1, a)
# array([1721, 1937, 4357,  233, 1261])

indices = np.argsort(f)
# array([3, 4, 0, 1, 2])

a[indices]
# array([[4, 3],
#        [5, 5],
#        [7, 2],
#        [7, 3],
#        [2, 8]])

Per @mozway's comment...this is significanlty faster since it allows Numpy to vectorize the function:根据@mozway 的评论...这明显更快,因为它允许 Numpy 向量化 function:

x,y = a.T
aa = (x ** 2 + y - 11) ** 2 + (x + y ** 2) ** 2 
indices = np.argsort(aa)
a[indices]

with the same result.结果相同。

So this works:所以这有效:

def f(x, y):
return (x**2 + y- 11)**2 + (x + y**2 -7)**2


def sortTuples(TupleList):
    output = [0, 0, 0, 0, 0]
    indexList = []
    for i in TupleList:
        x = i[0]
        y = i[1]
        indexList.append(f(x, y))
    indexList.sort()
    for i in TupleList:
        output[indexList.index(f(i[0], i[1]))] = i
    return output

Hope you find a nicer way to do this !希望你能找到更好的方法来做到这一点!

At least for small arrays, sorted is competitive to np.argsort , (especially if lists suffice for your task):至少对于小型 arrays 而言, sortednp.argsort具有竞争力,(特别是如果列表足以满足您的任务):

out = sorted(arr.tolist(), key=lambda x: (x[0]**2+x[1]-11)**2+(x[0]+x[1]**2-7)**2)

Output: Output:

[[4, 3], [5, 5], [7, 2], [7, 3], [2, 8]]

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

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