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
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)
No, you cannot use a negative integer as size, the size of an array represents the number of elements in it, –ve number of elements in an array makes no sense.
a = a.clip(min=0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With