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?
Asked
Active
Viewed 3,267 times
3
-
Yes. Numpy has both [advanced indexing](https://docs.scipy.org/doc/numpy-1.13.0/reference/arrays.indexing.html) and the [where](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.where.html) function for more complex queries. – armatita Nov 07 '17 at 15:55
-
If the answer below was useful to you, you should consider clicking on the check mark beside the answer to toggle it from greyed out to filled in. By now you have also earned the privilege to award upvotes on any question you find useful. – vestland Feb 19 '18 at 08:25
1 Answers
8
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

B. M.
- 18,243
- 2
- 35
- 54