1

I am looking for a way to find indices of an array of queries in a multidimensional array. For example:

arr = np.array([[17,  5, 19,  9],
   [18, 13,  3,  7],
   [ 8,  1,  4,  2],
   [ 8,  9,  7, 19],
   [ 6, 11,  8,  5],
   [11, 16, 13, 18],
   [ 0,  1,  2,  9],
   [ 1,  7,  4,  6]])

I can find indices for one query:

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

Is there any numpy solution to do this for multiple values replacing the following for loop?

for q in queries:
    np.where(arr==q)

If both the array and queries were one-dimensional, I could use searchsorted as this answer but it doesn't work for multidimensional arrays.

2 Answers 2

2

IIUC you may try this:

In[19]:np.where((arr==4)|(arr==5))
Out[19]: (array([0, 2, 4, 7], dtype=int64), array([1, 2, 3, 2], dtype=int64))
Sign up to request clarification or add additional context in comments.

Comments

1

You can get the indices of each matching value by zipping the results of your where function and then using the * dereferencing operator.

arr = np.array([[17,  5, 19,  9],
                [18, 13,  3,  7],
                [ 8,  1,  4,  2],  # (2, 1)
                [ 8,  9,  7, 19],
                [ 6, 11,  8,  5],
                [11, 16, 13, 18],
                [ 0,  1,  2,  9],  # (6, 1)
                [ 1,  7,  4,  6]])  # (7, 0)

>>> zip(*np.where(arr == 1))
[(2, 1), (6, 1), (7, 0)]

I'm not sure what your intended output is, but you can use a dictionary comprehension to show the index location for a given set of numbers, e.g.:

>>> {n: zip(*np.where(arr == n)) for n in range(5)}
{0: [(6, 0)],
 1: [(2, 1), (6, 1), (7, 0)],
 2: [(2, 3), (6, 2)],
 3: [(1, 2)],
 4: [(2, 2), (7, 2)]}

3 Comments

Thanks but I wanted to get np.where(arr == q) for different values of q!
Do you want the indices for each value of q or for all of the values of q?
>>> ix = np.in1d(arr.ravel(), [1,8,18]).reshape(arr.shape) ... >>> found = np.array(list(zip(np.where(ix)))) ... list is need in python 3.

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.