假设我有一个NumPy数组:
[[7 2]
[7 3]
[2 8]
[4 3]
[5 5]] 其中第0指数为x值,第1索引为y值。如何对这些值进行排序,以便当我将它们放入函数中时: (x ^2 +y-11)^2+(x+y^2-7)^2,它们根据结果按升序排序?所以排序后的值如下所示:
[[4 3]
[5 5]
[7 2]
[7 3]
[2 8]]数组可以有重复的。
我的想法之一是使用.argsort()方法,尽管我不知道如何实现这个方法。
谢谢!
发布于 2021-12-30 06:20:23
您可以应用沿着第一个轴的函数,得到一个具有函数值的一维数组。将结果传递给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的comment...this非常快,因为它允许Numpy将函数向量化:
x,y = a.T
aa = (x ** 2 + y - 11) ** 2 + (x + y ** 2) ** 2
indices = np.argsort(aa)
a[indices]结果是一样的。
发布于 2021-12-30 06:53:13
因此,这是可行的:
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希望你能找到一个更好的方法来做这件事!
发布于 2021-12-30 07:26:51
至少对于小型数组,sorted比np.argsort更有竞争力(特别是如果列表足以满足您的任务):
out = sorted(arr.tolist(), key=lambda x: (x[0]**2+x[1]-11)**2+(x[0]+x[1]**2-7)**2)输出:
[[4, 3], [5, 5], [7, 2], [7, 3], [2, 8]]https://stackoverflow.com/questions/70527981
复制相似问题