Reading records from file and sorting

Francesc Altet faltet at
Wed Nov 1 06:03:05 CST 2006

El dt 31 de 10 del 2006 a les 23:38 +0000, en/na George Sakkis va
> Is there a more elegant and/or faster way to read some records from a
> file and then sort them by different fields ? What I have now is too
> specific and error-prone in general:
> import numpy as N
> records = N.fromfile(a_file, dtype=N.dtype('i2,i4'))
> records_by_f0 = records.take(records.getfield('i2').argsort())
> records_by_f1 = records.take(records.getfield('i4',2).argsort())
> If there's a better way, I'd like to see it; bonus points for in-place
> sorting.

Why this is too specific or error-prone? I think your solution is quite
good. If what you want is a more compact way to write the above, you can
try with:

In [56]:records=numpy.array([(1,1),(0,2)], dtype="i2,i4")
In [57]:records[records['f0'].argsort()]
array([(0, 2), (1, 1)],
      dtype=[('f0', '<i2'), ('f1', '<i4')])
In [58]:records[records['f1'].argsort()]
array([(1, 1), (0, 2)],
      dtype=[('f0', '<i2'), ('f1', '<i4')])


Francesc Altet    |  Be careful about using the following code --
Carabos Coop. V.  |  I've only proven that it works,   |  I haven't tested it. -- Donald Knuth

Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo

More information about the Numpy-discussion mailing list