简体   繁体   中英

sorting by field numpy array

I wrote this code:

def readFile(filename):
    a = open(filename,'r')
    strs = np.array(0,dtype=[('nstr','d'),('test','f')])
    for i in a.readlines():
        if i[0] != '#':
            line = i.split()
            if len(line) > 0:
                tmp_strs = np.array(1,dtype=[('nstr','d'),('test','f')])
                tmp_strs['nstr'] = int(line[0])
                tmp_strs['test'] = float(line[1])
                strs = np.append(strs,tmp_strs)
    return strs

Now I'd like to sort this numpy array following the nstr field. This is easy done with the sort function of the numpy array. Anyway I bumped into a strange behavior which I cannot understand. If I do something like:

test = readFile(filename)
test.sort(order='nstr')

everything works fine. But if I change the return inside the function like

return strs.sort(order='nstr')

The return Value is None... could someone explain to me why this is happening? I do not have any explanation

The function you call is actually numpy.ndarray.sort , it will change ndarray itself but return None. See more detail here .
The function you want to call should be numpy.sort ,see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM