如何优化这个numpy 2D排序数组创建?(How can this numpy 2D sorted array creation be optimized?)

编程入门 行业动态 更新时间:2024-10-26 05:33:06
如何优化这个numpy 2D排序数组创建?(How can this numpy 2D sorted array creation be optimized?)

我有一个名为coefficients的NxM矩阵我要排序:

import numpy N = 10 M = 42 coefficients = numpy.random.uniform(size=(N, M))

我有一个名为order的数组order其中有N元素,表示coefficients行应该在的顺序:

order = numpy.random.choice(range(N), N, False)

我按排序order对coefficients进行排序:

coefficients = numpy.array([mag for (orig, mag) in sorted(zip(order, coefficients), key=lambda pair: pair[0])])

这可行,但它可能比它应该慢。 如果这是1D,我会使用fromiter ,但我不知道如何处理这个,因为它是2D。 我可以在这里进行优化吗?

I have a NxM matrix called coefficients that I want to sort:

import numpy N = 10 M = 42 coefficients = numpy.random.uniform(size=(N, M))

I have an array called order with N elements that says the order that the rows of coefficients should be in:

order = numpy.random.choice(range(N), N, False)

I'm sorting coefficients by sorting order:

coefficients = numpy.array([mag for (orig, mag) in sorted(zip(order, coefficients), key=lambda pair: pair[0])])

This works, but it's probably slower than it should be. If this was in 1D, I'd use fromiter, but I don't know how to tackle this since it's 2D. Is there an optimization I can make here?

最满意答案

要回答你的问题,只需coefficients[order.argsort()] :)

另见Numpy:按键排序功能 。

To answer your question, just coefficients[order.argsort()] is enough :)

See also Numpy: sort by key function.

更多推荐

本文发布于:2023-07-04 10:07:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   sorted   numpy   optimized   creation

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!