[Numpy-discussion] Efficient array equivalent to cmp(x,y)
Robert Kern
robert.kern@gmail....
Thu Sep 17 15:25:18 CDT 2009
[Please pardon the piggybacking. I didn't get the original.]
On Thu, Sep 17, 2009 at 15:19, Keith Goodman <kwgoodman@gmail.com> wrote:
> On Thu, Sep 17, 2009 at 1:13 PM, Kim Hansen <slaunger@gmail.com> wrote:
>> Hi,
>>
>> Is there an array-like function equivalent with the builtin method for the
>> Python single-valued comparison cmp(x,y)?
>>
>> What I would like is a cmp(a, lim), where a is an ndarray and lim is a
>> single value, and then I need an array back of a's shape giving the
>> elementwise comparison
>> array([cmp(a[0], lim), cmp(a[1], lim), ...])
>>
>> I can do it somewhat ackwardly doing this:
>>
>> In [1]: a = randint(5, size=10); print a
>> [0 2 4 1 3 0 3 4 0 1]
>> In [2]: lim = 2
>> In [3]: acmp = empty(a.shape, dtype='i1')
>> In [4]: acmp[a < lim] = -1
>> In [5]: acmp[a == lim] = 0
>> In [6]: acmp[a > lim] = 1
>> In [7]: acmp
>> Out[7]: array([-1, 0, 1, -1, 1, -1, 1, 1, -1, -1], dtype=int8)
>>
>> But that is not very elegant and since this is a computational bottleneck I
>> would rather like to avoid all the intermediate creations of three mask
>> arrays for fancy indexing in this example.
In [1]: a = np.array([0, 2, 4, 1, 3, 0, 3, 4, 0, 1])
In [2]: lim = 2
In [3]: np.sign(a - lim)
Out[3]: array([-1, 0, 1, -1, 1, -1, 1, 1, -1, -1])
--
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 NumPy-Discussion
mailing list