How to transform negative elements to zero without a loop?

Viewed 78205

If I have an array like

a = np.array([2, 3, -1, -4, 3])

I want to set all the negative elements to zero: [2, 3, 0, 0, 3]. How to do it with numpy without an explicit for? I need to use the modified a in a computation, for example

c = a * b

where b is another array with the same length of the original a

Conclusion

import numpy as np
from time import time

a = np.random.uniform(-1, 1, 20000000)
t = time(); b = np.where(a>0, a, 0); print ("1. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); b = a.clip(min=0); print ("2. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); a[a < 0] = 0; print ("3. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); a[np.where(a<0)] = 0; print ("4. ", time() - t)
a = np.random.uniform(-1, 1, 20000000)
t = time(); b = [max(x, 0) for x in a]; print ("5. ", time() - t)
  1. 1.38629984856
  2. 0.516846179962 <- faster a.clip(min=0);
  3. 0.615426063538
  4. 0.944557905197
  5. 51.7364809513
5 Answers

And just for the sake of comprehensiveness, I would like to add the use of the Heaviside function (or a step function) to achieve a similar outcome as follows:

Let say for continuity we have

a = np.array([2, 3, -1, -4, 3])

Then using a step function np.heaviside() one can try

b = a * np.heaviside(a, 0)

Note something interesting in this operation because the negative signs are preserved! Not very ideal for most situations I would say.

This can then be corrected for by

b = abs(b)

So this is probably a rather long way to do it without invoking some loop.

Related