-1

numpy NOOB.

How best to see if an element exists in a numpy array?

Example:

import numpy as np
a = np.array([[1, 2], [2, 3], [3, 4]])
[2, 4] in a
# This evaluates to True because there's 
# a 2 (somewhere) and a 4 (somewhere)
# but I want to match [2, 4] ONLY. So...
[2, 4] in a  # Would like this to be False
[2, 3] in a  # Would like this to be True
[3, 2] in a  # This too should be false (wrong order [3, 2] != [2, 3])

I've looked at np.where() and that doesn't seem to be what I'm looking for. I get a similar result to the above using np.isin([2, 4], a).

Don't need the index (though if it comes along for the ride that OK), just a boolean will suffice.

1
  • Agreed. I think it is a duplicate. Commented Oct 1, 2019 at 14:49

2 Answers 2

1

You're searching for 2 and 4 in a, try:

[[2, 4]] in a
Sign up to request clarification or add additional context in comments.

2 Comments

...but that evaulates to True.
I've added clarification. See edited question. If [2, 3] in array, do not want to match with [3, 2] (order important). Only want to match if elements and order agree. THANKS
0

This was flagged as duplicate of testing whether a Numpy array contains a given row wherein Tom10 provides the answer I sought:

np.equal([2, 3], a).all(axis=1).any()

1 Comment

When someone suggests a duplicate that you agree with, you should vote to close/flag as duplicate, or just accept the duplicate suggestion. You definitely shouldn't answer the question. If you have a solution that's not covered on the target, you can add an answer there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.