2

Given a matrix like the following:

A = np.array([[1,2,3],
          [3,4,5],
          [4,5,6]])

How can I pinpoint the index of an element of interest. For example, assume I would like to find the index of 2 in the first row of the np.array, like so: A[0,:].index(2), but clearly this does not work because A[0,:] is not a list.

1 Answer 1

3

You can compare the array to the value 2, and then use where.

For example, to find the location of 2 in the first row of A:

In [179]: np.where(A[0, :] == 2)[0]
Out[179]: array([1])

In [180]: j = np.where(A[0, :] == 2)[0]

In [181]: A[0, j]
Out[181]: array([2])

where also works with higher-dimensional arrays. For example, to find 2 in the full array A:

In [182]: i, j = np.where(A == 2)

In [183]: A[i,j]
Out[183]: array([2])
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.