pythonarraysnumpysortingnp.argsort

Python - argsort sorting incorrectly


What is the problem? Where am I doing wrong?

I am new to Python and I could not find the problem. Thanks a lot in advance for your help.

The code is

import numpy as np
users = [["Richard", 18],["Sophia", 16],["Kelly", 3],["Anna", 15],["Nicholas", 17],["Lisa", 2]]
users = np.array(users)
print(users[users[:, 1].argsort()])

Output should be

[['Lisa' '2']
['Kelly' '3']
['Anna' '15']
['Sophia' '16']
['Nicholas' '17']
['Richard' '18']]

But output is

[['Anna' '15']
['Sophia' '16']
['Nicholas' '17']
['Richard' '18']
['Lisa' '2']
['Kelly' '3']]

Solution

  • The numbers are being interpreted as strings (so '15' comes before '2', like 'ae' comes before 'b'). The fact that in the output, you see things like '15' with single quotes around it, is a clue to this.

    In order to create a numpy array which has a mixture of data types (strings for the names, ints for the numbers), you can create the array this way, specifying the data type as object:

    users = np.array(users, dtype=object)

    That will give the output you're looking for.