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

Question:

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

[[0, 2, 3, 5]]
Asked By: isaacmodi123

||

Answers:

The array is at the zeroth index of the tuple, so do
[A1[0].tolist()] and you will have your expected output.

Answered By: AxlLvy
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]

Answered By: user19077881

Use np.argwhere to find indices where condition is True (array elements that are non-zero):

res = np.argwhere(A[0] == 1).T

[[0 2 3 5]]
Answered By: RomanPerekhrest

As others have pointed out, you have a 2 dimensions array, so the function returns a tuple of array for each dimension. Still, this does not bring your desired output.

There 2 possible ways to achieve this, a classic version and the numpy version – which based on your input data (0 and 1) can be done with nonzero method:

# the classic version
A1 = [idx for idx, v in enumerate(A[0]) if v == 1]

# the numpy version
A1 = np.nonzero(A[0])

The nonzero can also be used to apply a different condition to get the indexes, let’s say equal to 2.

np.nonzero(A[0] == 2)

You can read more about the nonzero use cases here: numpy.nonzero doc.

Answered By: foobarna
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.