1

I want to check with most efficiency way (the fastest way), if some array (or list) is in numpy array. But when I do this:

import numpy

a = numpy.array(
    [
        [[1, 2]],
        [[3, 4]]
    ])

print([[3, 5]] in a)

It only compares the first value and returns True

Somebody knows, how can I solve it? Thank you.

Foreen
  • 369
  • 2
  • 17
  • 1
    Does this answer your question? [Iterating over Numpy matrix rows to apply a function each?](https://stackoverflow.com/questions/16468717/iterating-over-numpy-matrix-rows-to-apply-a-function-each) – anurag Jan 27 '21 at 15:26
  • Thank you, this helped me, too. – Foreen Jan 28 '21 at 14:49
  • for your original data, is only the matrix `a` large or the query matrix is also large? – anurag Feb 01 '21 at 13:23

2 Answers2

1

You could just add tolist() in your last line:

print([[3, 5]] in a.tolist())

gives

False
joostblack
  • 2,465
  • 5
  • 14
  • I do not know what your application is but I think you can drop the double brackets and instead use single brackets. – joostblack Jan 27 '21 at 15:31
  • This works! Thank you, but it is really slow. I have big data series and with them it takes more than 1 minute. Is there any faster solution? – Foreen Jan 27 '21 at 15:36
1

Your question seems to be a duplicate of: How to match pairs of values contained in two numpy arrays

In any case, something like the first answer should do it if I understand correctly:

import numpy

a = numpy.array(
    [
        [[1, 2]],
        [[3, 4]]
    ])

b = numpy.array([[3,5]])

print((b[:,None] == a).all(2).any(1))

Which outputs:

array([False,  True])
Leonardo Viotti
  • 476
  • 1
  • 5
  • 15
  • Thank you! This works, it is faster than solution from joostblack, but it still takes a long time on my big data series. Is there any other faster solution? Thank you. – Foreen Jan 27 '21 at 15:43