Finding string elements of an array in another array

Viewed 574

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

Simple for loop should do:

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

Or

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

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])

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]

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)
        

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])
Related