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

Locating indices with element 1 and converting to a list in Python

I have an array A. I want to identify all indices with element 1 and print as a list. But I am getting an error. I present the expected output.

import numpy as np

A=np.array([[1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0]])
A1=np.where(A[0]==1)
A1.tolist()
print(A1)

The error is

in <module>
    A1.tolist()

AttributeError: 'tuple' object has no attribute 'tolist'

The expected output 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

[[0, 2, 3, 5]]

>Solution :

A1 = [i for i,x in enumerate(A[0]) if x == 1]

or

A1=list(np.where(A[0]==1)[0])

You have an array inside an array hence A[0]

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