How to apply a function only to certain elements of an array?

I have an array x , and I want to apply the function f to every element in the matrix that satisfies some condition. Does Numpy offer a mechanism to facilitate this?

Here is an example. My matrix x should only contain elements in the exclusive range (0, 1) . However, due to rounding errors, some elements may be 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 done after I accepted the prompt .) Another way to do this is to use numpy.clip .

+4
source share
3 answers

You can do it:

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

The reason for this is that a==0 returns a logical array, just like Valera Gorbunov mentioned in their answer:

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

Then you use this array as an index for a , which provides elements where True , but not where False . You can do a lot there, see http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

+9
source

Sorry, this is not more specific, but you can create a logical array with a TRUE value for each position that matches your condition, and FALSE for those who do not.

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

Example Boolean Matrix

+3
source

You can use map() as described in http://docs.python.org/2/tutorial/datastructures.html#functional-programming-tools :

 def applyEpsilon(value): myEpsilon = 0.001 if value == 0: return myEpsilon elif value == 1: return 1-myEpsilon return value inputList = [0, 0.25, 0.5, 0.75, 0.99, 1] print map(applyEpsilon, inputList) 

Productivity:

 [0.001, 0.25, 0.5, 0.75, 0.99, 0.999] 
+2
source

All Articles