0

Let´s say I have 2 numpy arrays:

an_array=np.array(['1601-3003-2105','3200-0000-0001','3200-0000-0002','93043','K036095','K036096'])
another_array=np.array(['3200-0000-0001','701450491A4CU',16])

I want to iterate over these arrays like this:

for elem in an_array:
    if elem in another_array:
        print(True)
    else:
        print(False)

and then I am getting this output

enter image description here

How could I get the matching element as the resulting output, in this case 3200-0000-0001 element?

1
  • 1
    print(elem) ? Commented Aug 23, 2021 at 13:20

3 Answers 3

1

Syntax sugar will help

ans=[i for i in an_array if i in another_array]
Sign up to request clarification or add additional context in comments.

1 Comment

This works just as well, even better, if you use lists (instead of creating arrays).
0

np.intersect1d would do.

np.intersect1d(an_array, another_array)

returns :

array(['3200-0000-0001'], dtype='<U14')

1 Comment

Thanks to cyril, your answer worked perfectly.
0

I assume you mean from the another_array as if you mean from an_array you can access the object directly as it is the elem object.

In this case you can do

itemindex = np.where(another_array==elem)
item = another_array[itemindex]

the first line returns the index in the array of the object and then the second line gets the object

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.