I am trying to code a numpy function that shows the number of values that are less than 0 within an array. How would I be able to do that?
import numpy as np
array = np.array([10,4,3,5,6,67,3,-12,5,-6,-7])
Expected Output:
3
Just compare the array against a value (i.e. less than zero for negative values), then call sum since, you only need the count.
>>> array = np.array([10,4,3,5,6,67,3,-12,5,-6,-7])
>>> (array<0).sum()
3
And if you want those values instead of just count, then use the masking to get those values
>>> array[array<0]
array([-12, -6, -7])
you can print it with:
print(sum([i for i in array if i < 0]))
you can set it to a variable with:
lessThanZero = sum([i for i in array if i < 0])
did a benchmark (of sorts)
import datetime
import numpy
numpySum=0
forLoop=0
test = numpy.array([1,2,3,4,5,6,7,8,9,0])
for k in range(1000):
a = datetime.datetime.now()
for j in range(100):
z = (test<5).sum()
b = datetime.datetime.now() - a
a = datetime.datetime.now()
for j in range(100):
z = [i for i in test if i < 5]
a = datetime.datetime.now() - a
if b<a:numpySum+=1
else: forLoop+=1
print(numpySum, forLoop)
output over 3 runs:
633 367
752 248
714 286
appears the numpy sum is faster :D
This was for an array of size 10. I tried again with size 1000, and the numpy sum answer won every time!
(array < 0).sum().