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

Getting indices using conditional list comprehension

I have the following np.array:

my_array=np.array([False, False, False, True, True, True, False, True, False, False, False, False, True])

How can I make a list using list comprehension of the indices corresponding to the True elements. In this case the output I’m looking for would be [3,4,5,7,12]

I’ve tried the following:

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

cols = [index if feature_condition==True for index, feature_condition in enumerate(my_array)]

But is not working

>Solution :

why specifically a list comprehension?

>>> np.where(my_array==True)
(array([ 3,  4,  5,  7, 12]),)

this does the job and is quicker. The list solution would be:

>>> [index for index, feature_condition in enumerate(my_array) if feature_condition == True]
[3, 4, 5, 7, 12]

Accepted answer of this explains the confusion of the ordering: if/else in a list comprehension

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