One of the string arrays is not sorted

Viewed 48
import numpy as np

arr1=np.array(['102.0','135.0','135.0','152.0','93.0','95.0'])

print(arr1)
arr1.sort()
print(arr1)

print()

arr2=np.array(['86.0','82.0','84.0','87.0','95.0','89.0'])

print(arr2)
arr2.sort()
print(arr2)

The first array is not sorted, but second is sorted, why?. I cannot find the mistake.

2 Answers

The sort function only sorts integers correctly, so for strings it sorts by the first character so the ones over a hundred will be before the one that are ninety something, the way to fix would be to change them to integers:

import numpy as np

arr1=np.array(['102.0','135.0','135.0','152.0','93.0','95.0'])
arr1 = arr1.astype(float)
print(arr1)
arr1.sort()
print(arr1)

print()

arr2=np.array(['86.0','82.0','84.0','87.0','95.0','89.0'])
arr2 = arr2.astype(float)
print(arr2)
arr2.sort()
print(arr2)

As @juanpa.arrivillaga mentioned:

it sorts lexicographically by all the characters

You are sorting strings the sort function is properly sorting the string elements (e.g. "102.0" comes before "93.0"). If you want to sort integers properly, remove the double-quotes around all your elements:

arr1=np.array([102.0,135.0,135.0,152.0,93.0,95.0])
arr2=np.array([86.0,82.0,84.0,87.0,95.0,89.0])
Related