0

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']
5
  • what is wrong about it? it looks fine from here Commented Mar 3, 2015 at 8:28
  • It should sort it as ['A 0' 'A 1' 'A 10' 'A 20' 'A 100' 'A 200']. Commented Mar 3, 2015 at 8:31
  • You are sorting strings! Why do you expect anything but a lexical sorting here? Commented Mar 3, 2015 at 8:34
  • 1
    What's the purpose of using numpy if you're handling strings anyway? Strings are storted in lexicographical order. Commented Mar 3, 2015 at 8:35
  • 1
    Sounds like you're looking for a natural sort. Python doesn't come with one, and NumPy certainly isn't the library to look for one in. Commented Mar 3, 2015 at 9:00

2 Answers 2

1

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)], ...
Sign up to request clarification or add additional context in comments.

Comments

0

Then you should tell it how it is supposed to do it, like for example:

lst.sort(key=lambda s: int(s[2:]))

1 Comment

This is not a NumPy solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.