Paul Manta
Paul Manta

Reputation: 31567

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.

Upvotes: 5

Views: 2998

Answers (3)

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

Upvotes: 3

askewchan
askewchan

Reputation: 46530

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

Upvotes: 9

neilr8133
neilr8133

Reputation: 152

You can use map() as documented at 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)

Yields:

[0.001, 0.25, 0.5, 0.75, 0.99, 0.999]

Upvotes: 2

Related Questions