Search code examples
pythonnumpymultidimensional-arrayexp

Numpy array apply a function only to some elements


I have a numpy array let's say that has a shape (10,10) for example. Now i want to apply np.exp() to this array, but just to some specific elements that satisfy a condition. For example i want to apply np.exp to all the elements that are not 0 or 1. Is there a way to do that without using for loop that iterate on each element of the array?


Solution

  • This is achievable with basic numpy operations. Here is a way to do that :

    A = np.random.randint(0,5,size=(10,10)).astype(float)  # data
    goods = (A!=0) & (A!=1)  # 10 x 10 boolean array
    A[goods] = np.exp(A[goods])  # boolean indexing