How to apply function to only certain array elements?

indexing, numpy, python

Solution

You can do this:

a = np.array([0,.1,.5,1])
epsilon = 1e-5
a[a==0] += epsilon
a[a==1] += -epsilon

The reason this works is that `a==0` returns a boolean array, just like what Валера Горбунов referred to in their answer:

In : a==0
Out: array([True, False, False, False], dtype=bool)

Then you're using that array as an index to `a`, which exposes the elements where `True` but not where `False`. There's a lot that you can do with this, see http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

Problem

I have an array `x` and I want to apply a function `f` to every item in the matrix that meets some condition. Does Numpy offer a mechanism to make this easy? Here's an example. My matrix `x` is supposed to contain only elements in the exclusive range `(0, 1)`. However, due to rounding errors, some elements can be equal to `0` or `1`. For every element in `x` that is exactly `0` I want to add `epsilon` and for every element that is exactly `1` I want to subtract `epsilon`. Edit: (This edit was made after I had accepted askewchan's answer.) Another way to do this is to use `numpy.clip`.

Original source

Related problems