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

Pandas – return value of column

I have a df with categories and thresholds:

cat t1 t2 t3 t4
a   2  4  6  8
b   3  5  7  0
c   0  0  1  0

My end goal is to return the column name given category and score. I can select a row using a cat variable:

df[df['cat'] == cat]

How do I now return the column name that is closest to the score (rounded down)? (c, 3) -> t3

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

>Solution :

You can compute the absolute difference to your value and get the index of the minimum with idxmin:

value = 3
cat = 'c'

(df.set_index('cat')
   .loc[cat]
   .sub(value).abs()
   .idxmin()
 )

Output: 't3'

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