Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading