[Numpy-discussion] Efficient array equivalent to cmp(x,y)
Kim Hansen
slaunger at gmail.com
Thu Sep 17 16:13:58 EDT 2009
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.
Is there a simpler/more elegant way to acheive the same result?
Thanks in advance,
Kim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20090917/8c48b15d/attachment.html>
More information about the NumPy-Discussion
mailing list