# [Numpy-discussion] How do I do this?

Keith Goodman kwgoodman@gmail....
Fri Aug 29 16:57:22 CDT 2008

```On Fri, Aug 29, 2008 at 2:52 PM, Keith Goodman <kwgoodman@gmail.com> wrote:
> On Fri, Aug 29, 2008 at 2:49 PM, Keith Goodman <kwgoodman@gmail.com> wrote:
>> On Fri, Aug 29, 2008 at 2:35 PM, Christopher Barker
>> <Chris.Barker@noaa.gov> wrote:
>>> 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])
>>
>> Does this work?
>>
>>>> x
>>   array([ 1.,  2., -5., -1.,  0.])
>>>> np.sign(x) * np.clip(np.absolute(x), 2, np.inf)
>>   array([ 2.,  2., -5., -2.,  0.])
>
> Oh, I guess 0 is less than 2.

If you only have integers then

>> x
array([ 1,  2, -5, -1,  0])
>> np.sign(x+1e-16) * np.maximum(np.abs(x), 2)
array([ 2.,  2., -5., -2.,  2.])
```