Reputation: 6496
I have array elements of the form:
['A 0', 'A 10', 'A 1', 'A 100', 'A 20', 'A 200']
When I try to sort it with np.sort(), it does not sort properly. How to sort the array properly?
Code
import numpy as np
A = np.array(['A 0', 'A 10', 'A 1', 'A 100', 'A 20', 'A 200'])
A = np.sort(A)
print A
Output
['A 0' 'A 1' 'A 10' 'A 100' 'A 20' 'A 200']
Desired output
['A 0' 'A 1' 'A 10' 'A 20' 'A 100' 'A 200']
Upvotes: 0
Views: 603
Reputation: 249502
The easiest way is to load the data as two separate columns: the text part and the numeric part. This works:
>>> lst = ['A 0', 'A 10', 'A 1', 'A 100', 'A 20', 'A 200']
>>> A = np.loadtxt(lst, dtype=[('text', 'S4'), ('numbers', int)])
>>> A.sort(order='numbers')
>>> A
array([('A', 0), ('A', 1), ('A', 10), ('A', 20), ('A', 100), ('A', 200)], ...
Upvotes: 1
Reputation: 8982
Then you should tell it how it is supposed to do it, like for example:
lst.sort(key=lambda s: int(s[2:]))
Upvotes: 0