[SciPy-user] Best way to test several values

Robert Kern robert.kern at gmail.com
Mon Oct 20 10:15:06 EDT 2008


On Mon, Oct 20, 2008 at 09:05, Jose Luis Gomez Dans <josegomez at gmx.net> wrote:
> Hi,
> I have a 2D array of numbers, and I want to use "where" to effectively mask
> bits of the array out. Essentially, if any element in this 2D array of
> numbers belongs to a given list (stored as a 1D array), the condition should
> be e.g., True.
>
> Up to now, I have used numpy.any ( data==QA ), where data is a single element
> of my 2D array, and QA is my acceptance values list. However, I need to loop
> through elements, and is taking a long time.
>
> Any hints? numpy/scipy seems to have a plethora of clever functions to this
> sort of thing efficiently!

In [12]: a = random.randint(0, 10, (10,10))

In [13]: b = reshape(a, a.shape + (1,))

In [14]: QA = array([2,4,6])

In [15]: QA2 = reshape(QA, (1,1,-1))

In [16]: (b == QA2).any(axis=-1)
Out[16]:
array([[ True,  True, False, False,  True, False, False, False, False,
         True],
       [ True, False, False, False,  True,  True,  True, False, False,
        False],
       [ True,  True, False, False,  True,  True, False,  True,  True,
        False],
       [ True, False, False, False, False, False,  True, False,  True,
        False],
       [False,  True, False, False,  True, False, False, False,  True,
         True],
       [False, False,  True, False, False, False, False,  True, False,
        False],
       [False, False,  True,  True,  True,  True, False, False, False,
        False],
       [ True, False,  True, False, False, False, False, False, False,
        False],
       [False, False, False, False, False, False, False, False, False,
         True],
       [ True, False, False, False, False, False, False, False,  True,
         True]], dtype=bool)

In [17]: a[Out[16]]
Out[17]:
array([6, 2, 6, 4, 6, 4, 6, 2, 2, 4, 2, 6, 2, 2, 6, 4, 2, 6, 4, 2, 6, 4, 6,
       2, 6, 2, 6, 4, 4, 2, 2, 4, 4])

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the SciPy-User mailing list