How do you construct an array suitable for numpy sorting?

Posted by Alex on Stack Overflow See other posts from Stack Overflow or by Alex
Published on 2009-02-18T08:45:47Z Indexed on 2010/04/10 7:53 UTC
Read the original article Hit count: 734

Filed under:
|
|
|

I need to sort two arrays simultaneously, or rather I need to sort one of the arrays and bring the corresponding element of its associated array with it as I sort. That is if the array is [(5, 33), (4, 44), (3, 55)] and I sort by the first axis (labeled below dtype='alpha') then I want: [(3.0, 55.0) (4.0, 44.0) (5.0, 33.0)]. These are really big data sets and I need to sort first ( for nlog(n) speed ) before I do some other operations. I don't know how to merge my two separate arrays though in the proper manner to get the sort algorithm working. I think my problem is rather simple. I tried three different methods:

import numpy
x=numpy.asarray([5,4,3])
y=numpy.asarray([33,44,55])

dtype=[('alpha',float), ('beta',float)]

values=numpy.array([(x),(y)])
values=numpy.rollaxis(values,1)
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')
print "Try 1:\n", values

values=numpy.empty((len(x),2))
for n in range (len(x)):
        values[n][0]=y[n]
        values[n][1]=x[n]
print "Try 2:\n", values
#values = numpy.array(values, dtype=dtype)
#a=numpy.array(values,dtype=dtype)
#q=numpy.sort(a,order='alpha')

###
values = [(x[0], y[0]), (x[1],y[1]) , (x[2],y[2])]
print "Try 3:\n", values
values = numpy.array(values, dtype=dtype)
a=numpy.array(values,dtype=dtype)
q=numpy.sort(a,order='alpha')

print "Result:\n",q

I commented out the first and second trys because they create errors, I knew the third one would work because that was mirroring what I saw when I was RTFM. Given the arrays x and y (which are very large, just examples shown) how do I construct the array (called values) that can be called by numpy.sort properly?

*** Zip works great, thanks. Bonus question: How can I later unzip the sorted data into two arrays again?

© Stack Overflow or respective owner

Related posts about python

Related posts about numpy