Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
Marco Miglionico Avatar asked Nov 05 '25 14:11

Marco Miglionico


1 Answers

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
like image 183
B. M. Avatar answered Nov 08 '25 08:11

B. M.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!