[Numpy-discussion] Masking an array with another array

josef.pktd@gmai... josef.pktd@gmai...
Thu Apr 23 08:08:11 CDT 2009


On Thu, Apr 23, 2009 at 1:24 AM, Gökhan SEVER <gokhansever@gmail.com> wrote:
> Ahaa,,
>
> Thanks Gaël. That method is more elegance than the previous inputs, and the
> simplest of all.
>
> Although one line of "import this" says:
>
> There should be one-- and preferably only one --obvious way to do it.
>
> I always find many different ways of implementing ideas in Python world.
>
> Gökhan
>
>
> On Thu, Apr 23, 2009 at 12:16 AM, Gael Varoquaux
> <gael.varoquaux@normalesup.org> wrote:
>>
>> On Wed, Apr 22, 2009 at 04:21:05PM -0500, Gökhan SEVER wrote:
>> >    Could you please give me some hints about how to mask an array using
>> >    another arrays like in the following example.
>>
>> >    In [14]: a = arange(5)
>>
>> >    In [15]: a
>> >    Out[15]: array([0, 1, 2, 3, 4])
>>
>> >    and my secondary array is "b"
>>
>> >    In [16]: b = array([2,3])
>>
>> >    What I want to do is to mask a with b values and get an array of:
>>
>> >    array([False, False, True, True,  False], dtype=bool)
>>
>> This is an operation on 'sets': you are testing if members of a are 'in'
>> b. Generally, set operations on arrays can be found in
>> numpy.lib.arraysetops. I believe what you are interested in is
>> setmember1d.
>>
>> HTH,
>>
>> Gaël

setmember1d is very fast compared to the other solutions for large b.

However, setmember1d requires that both arrays only have unique elements.

So it doesn't work if, for example, your first array is a data vector
with member ship in different groups (therefore not only uniques), and
the second array is the sub group that you want to check.

Josef

>>> a = np.array([7, 5, 1, 3, 3, 0, 0, 8, 8, 2])
>>> b = np.array([0, 1])
>>> np.setmember1d(a,b)
array([False, False,  True,  True, False,  True,  True,  True, False,
False], dtype=bool)

>>> (a[:,np.newaxis]==b).any(1)
array([False, False,  True, False, False,  True,  True, False, False,
False], dtype=bool)


More information about the Numpy-discussion mailing list