Search code examples
python-3.xnumpyprettytable

In a numpy record array, how can you order the elements based off a value in the record?


I have the following numpy record array.

name       module           offset

filter-2   filter_module    0x000020

filter-3   filter_module    0x000042

filter-1   filter_module    0x000014

I want to be able to detect which offset value is the smallest and the order them in rising order. An desirable output would be.

name       module           offset

filter-1   filter_module    0x000014

filter-2   filter_module    0x000020

filter-3   filter_module    0x000042

Here is the code where I generated this numpy array

instance_dtype={
    'names' : ('name','module','offset'),
    'formats' : ('U20','U20','U20')}

instance= np.zeros(5,instance_dtype)
i=0

for node in xml_file.iter():
    if node.tag=="instance":
        attribute=node.attrib.get('name')

inst=  (node.attrib.get('name'),node.attrib.get('module'),node.attrib.get('offset'))
        instance[i]=inst
        i=i+1
 print('%10s,%15s,%5s'%tuple(rec))

How can I read the offset values figure out which is the lowest, then reorganize the array to start from the smallest offset value to the largest?


Solution

  • Any of the 'columns' can be accessed by name:

    inst['name']
    inst['module']
    

    np.sort takes an order parameter - see its documentation for an example

    Without recreating your array, I think this should work:

    inst1 = np.sort(inst, order='offset')
    

    inst1 should print with 'rows' sorted by 'offset'.

    You could also try argsort on the specific field:

    idx = np.argsort(inst['offset'])
    inst[idx]