Popular recipes tagged "argsort"http://code.activestate.com/recipes/tags/argsort/2012-03-14T15:14:11-07:00ActiveState Code RecipesFast Sorting of n dimensional array by first dimension (Python)
2012-03-14T15:14:11-07:00Garretthttp://code.activestate.com/recipes/users/4181290/http://code.activestate.com/recipes/578074-fast-sorting-of-n-dimensional-array-by-first-dimen/
<p style="color: grey">
Python
recipe 578074
by <a href="/recipes/users/4181290/">Garrett</a>
(<a href="/recipes/tags/argsort/">argsort</a>, <a href="/recipes/tags/lists/">lists</a>, <a href="/recipes/tags/numpy/">numpy</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/sorting/">sorting</a>).
</p>
<p>I have looked far and wide for code for fast sorting of n dimensional arrays by the first element, for example if I had the array: <br />
ray = [[1,2,3,7,5][10,11,12,13,14]] </p>
<p>I would want it to come out as
ray = [[1,2,3,5,7][10,11,12,14,13]]</p>
<p>There are several ways to do this. One is
zipped = zip(<em>ray)
zipped.sort()
ray = zip(</em>zipped)</p>
<p>but this is extremely slow. Numpy has a much faster way to do it, but it wasn't immediately apparent.</p>
<p>if the above were a numpy array you could simply do the following:
indexes = numpy.argsort(ray[0])
for n in xrange(len(ray))
ray[n] = ray[n][indexes]</p>
<p>I did a time test of the two methods below.</p>