Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform negative elements to zero without a loop?

Tags:

python

numpy

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
like image 723
Ruggero Turra Avatar asked Aug 02 '10 21:08

Ruggero Turra


People also ask

Can we put negative elements in array?

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.


1 Answers

a = a.clip(min=0) 
like image 162
Ruggero Turra Avatar answered Sep 21 '22 13:09

Ruggero Turra