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

How do I sort a dataframe by distance from zero value

I’ll start by saying I am a Python beginner, I did try and find an answer to this via similar questions but I’m struggling to grasp some of the solutions in order to tailor them for my own use.

If I have a Pandas dataframe as follows:

enter image description here

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

What code would I need in order to sort it as per the below whilst excluding the 0 value.
I would ideally want to grab the value closest to zero (assuming this is possible).

enter image description here

>Solution :

IIUC, you can set abs as a key parameter of pandas.DataFrame.sort_values.

Try this :

out = df.sort_values(by="Score", key=abs)

# Output :

print(out)

     Name  Score
3  maggie      0
2   sally     -5
1    jane    -10
4   peter     15
6    andy     25
0     bob    -30
5    mike     50
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