Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply function to only certain array elements?

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.

like image 779
Paul Manta Avatar asked Mar 08 '13 20:03

Paul Manta


2 Answers

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

like image 171
askewchan Avatar answered Nov 06 '22 06:11

askewchan


Sorry this isn't more concrete, but you could create a Boolean array that has a TRUE value for every position that meets your condition and FALSE for those that don't.

For something like [0, 1, 0, 0] when testing for 1 you will get an array [FALSE, TRUE, FALSE, FALSE]. In which case you can do [0, 1, 0, 0] - (epsilon)[FALSE, TRUE, FALSE, FALSE] and leave the 0 values unaffected.

Boolean Array Example

like image 42
Валера Горбунов Avatar answered Nov 06 '22 05:11

Валера Горбунов