TransWikia.com

Finding string elements of an array in another array

Stack Overflow Asked by P Emt on December 20, 2021

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

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

Answered by Paul Panzer on December 20, 2021

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

Answered by Harben on December 20, 2021

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)
        

Answered by Keiron Stoddart on December 20, 2021

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]

Answered by Ann Zen on December 20, 2021

Simple for loop should do:

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

Or

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

Answered by nav610 on December 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP