-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.

PartialOrder
  • 2,870
  • 3
  • 36
  • 44

2 Answers2

1

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

[[2, 4]] in a
Rafa Guillermo
  • 14,474
  • 3
  • 18
  • 54
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()
PartialOrder
  • 2,870
  • 3
  • 36
  • 44
  • 1
    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. – cigien Jan 09 '22 at 01:35