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

Numpy Array replace booleans with string depending on position of "True"

To process to output of a multi-class classification I’d like to process a numpy array in such a way, that every True from the first column results in a class1 and a True in class2 correspondingly. A row with no True‘s should be translated into class3.

My initial array looks like that:

[[True False],
[False False],
[False True],
...
[True False],
[False True]]

(A row containing [True True] can not arise.)

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 I’d like to get out is:

[class1 class3 class2 ... class1 class2]

Ideas for an elegant and fast approach are highly appreciated. Thanks in advance!

>Solution :

You can use numpy.select.

import numpy as np
cls = np.array([[True, False],[False, False],[False, True],[True, False],[False, True]])

mask = cls.any(-1)
condlist = [(mask & cls[..., 0]), 
            (mask & cls[..., 1]),
            (mask==False)]
choicelist = ['class1', 'class2', 'class3']
res = np.select(condlist, choicelist, 'Not valid')
print(res)

Output:

['class1' 'class3' 'class2' 'class1' 'class2']
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