我有一个名为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.
更多推荐
发布评论