[Numpy-discussion] How do I do this?
Christopher Barker
Chris.Barker at noaa.gov
Fri Aug 29 17:35:59 EDT 2008
HI all,
I need to do something I thought would be simple -- set all the values
of an array to some minimum. so I did this:
>>> min_value = 2
>>> a = np.array((1, 2, 3, 4, 5,))
>>> np.maximum(a, min_value)
array([2, 2, 3, 4, 5])
all was well... then I realized that a could have negative numbers in
in, and I really wanted the absolute value to be greater than than minimum:
>>> a = np.array((1, 2, 3, 4, -5,))
>>> np.maximum(a, min_value)
array([2, 2, 3, 4, 2])
oops!
so I added a sign() and abs():
>>> np.sign(a) * np.maximum(np.abs(a), min_value)
array([ 2, 2, 3, 4, -5])
all was well. However it turns out a could contain a zero:
>>> a = np.array((0, 1, 2, 3, 4, -5,))
>>> np.sign(a) * np.maximum(np.abs(a), min_value)
array([ 0, 2, 2, 3, 4, -5])
Darn! I want that zero to become a 2, but sign(0) = 0, so that doesn't
work.
How can I do this without another line of code special casing the 0,
which isn't that big I deal, but it seems kind of ugly...
>>> a[a==0] = min_value
>>> np.sign(a) * np.maximum(np.abs(a), min_value)
array([ 2, 2, 2, 3, 4, -5])
thanks,
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list