I have a text file contain two columns and I want to sort the first column from smaller values to larger values and sort the second column according to the first column and then save it to the the same file. I used this method but did not work
data4 = np.loadtxt('crate&J.txt')
a = data4[:,0]
b = data4[:,1]
ind = np.lexsort((b,a))
What should I do?
Lexsort don't sort array, it returns indices. Say for example from docs:
>>> first_names = ('Heinrich', 'Galileo', 'Gustav')
>>> surnames = ('Hertz', 'Galilei', 'Hertz')
>>> data = np.array([first_names, surnames])
>>> ind = np.lexsort(data)
>>> data[:, ind]
array([['Galileo', 'Gustav', 'Heinrich'],
['Galilei', 'Hertz', 'Hertz']],
dtype='|S8')
so I suppose for your case you need
ind = np.lexsort(data.T[[1,0], :]) # you sort columns, not rows, second row first
np.savetxt('crate&J.txt', data4[ind,:])
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.