0
arr = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])

I'm trying to get the indices of arr when arr==1.

I thought this would work but it doesn't give the expected output:

>>> np.where(arr==1)
   (array([0], dtype=int64), array([0], dtype=int64), array([0], dtype=int64))
4
  • 2
    What output do you expect? Commented Jun 23, 2020 at 4:51
  • 1
    it is giving you the expected output you get 1 at [0][0][0] Commented Jun 23, 2020 at 4:54
  • sorry, you are right, I misunderstood the output... By the way how would you do this for multiple numbers like arr==1 or 2 or 3? Commented Jun 23, 2020 at 4:58
  • arr[ np.where( arr=1 )] should display 1. where/nonzero gives a tuple of arrays suitable for indexing. Here its 3 arrays since arr is 3d. Commented Jun 23, 2020 at 4:59

3 Answers 3

1

If you change arr:

arr = np.array([[[1,2],[3,4]],[[1,1],[7,8]]])

and you will get

np.where(arr==1)
# (array([0, 1, 1]), array([0, 0, 0]), array([0, 0, 1]))

it is mean:

arr[0][0][0] == 1
arr[1][0][0] == 1
arr[1][0][1] == 1

When you want display coordinate in one row:

np.array(np.where(arr==1)).T
# array([[0, 0, 0],[1, 0, 0],[1, 0, 1]])
Sign up to request clarification or add additional context in comments.

1 Comment

arr[1,0,1] is nicer looking numpy.
1

For multiple numbers, you can mix np.where and np.isin functions:

Here is an example:

import numpy as np

val = np.array([1,2,3])
arr = np.array([[[1,2],[3,4]],[[5,6],[7,8]]])

loc_i, loc_j, loc_k = np.where(np.isin(arr, val))
print('locations:')
[print(f'({loc_i[i]},{loc_j[i]},{loc_k[i]})') for i in range(loc_i.size)]

Comments

0

An interesting option is to use argwhere to get indices of elements in question.

To present a more instructive example, assume that we want indices of your arr where the value is <= 3.

The code to get them is np.argwhere(arr <= 3), getting:

array([[0, 0, 0],
       [0, 0, 1],
       [0, 1, 0]], dtype=int64)

​Meaning that the "wanted" elemens are:

arr[0, 0, 0], arr[0, 0, 1], arr[0, 1, 0],

If you want e.g. to print indices of the "wanted" elements and their values, you can run:

for ind in np.argwhere(arr <= 3):
    print(f'{ind}: {arr.__getitem__(tuple(ind))}')

The result is:

[0 0 0]: 1
[0 0 1]: 2
[0 1 0]: 3

Note also that my code works regardless of the number of dimensions in your array, whereas in other solutions the number of dimensions is somehow "fixed" in the code.

1 Comment

All argwhere does is np.transpose(np.where(...))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.