P Emt
P Emt

Reputation: 35

Finding string elements of an array in another array

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.

Upvotes: 2

Views: 1225

Answers (5)

Paul Panzer
Paul Panzer

Reputation: 53029

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

Upvotes: 0

Harben
Harben

Reputation: 1856

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

Upvotes: 1

Keiron Stoddart
Keiron Stoddart

Reputation: 378

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)
        

Upvotes: 0

nav610
nav610

Reputation: 791

Simple for loop should do:

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

Or

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

Upvotes: 1

Red
Red

Reputation: 27567

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]

Upvotes: 0

Related Questions