2

I have two sorted arrays h and M:

h = np.array(['blue', 'red', 'white'])
M = np.array(['blue', 'green', 'orange', 'red', 'white'])

and would like to find the indices at which each element of h appears in M

Can I np.where for this?

Also, it can be the case that an element of h might not appear in M and in this case, I don't require the index for it. The elements do not repeat.

5 Answers 5

1

This is another way and is a one-liner that will return an ndarray of the indices of the matches.

np.nonzero(np.in1d(M, h))[0]

Output

array([0, 3, 4])
Sign up to request clarification or add additional context in comments.

Comments

1

Simple for loop should do:

for value in h: 
    print(np.where(M==value))

Or

print(np.where([M==value for value in h]))

1 Comment

thank you - is it possible to convert this in one line where it will store the indices? also, there is the second piece that i edited above just now
0

Here is how:

import numpy as np

h = np.array(['blue', 'red', 'white'])
M = np.array(['blue', 'green', 'orange', 'red', 'white'])

i = np.where([h == i for i in M])
print(i[0])

Output:

[0 3 4]

Comments

0

If you are looking for the indices I would use Python's built-in enumerate function. Like this:

indices = []
for ind, val in enumerate(M):
    if val in h:
        indices.append(ind)
        

Comments

0

Taking advantage of M and h being sorted:

h = np.array(['blue', 'red', 'white'])
M = np.array(['blue', 'green', 'orange', 'red', 'white'])

# find indices
idx = M.searchsorted(h)
# avoid index error if last entry of h is larger than last of M
idx = idx[:idx.searchsorted(len(M))]
# filter out unmatched elements
idx[M[idx]==h]
# array([0, 3, 4])

Comments

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.