1

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
1
  • 1
    You can get a boolean array satisfying your condition and call sum: (array < 0).sum(). Commented Jul 29, 2021 at 18:14

2 Answers 2

6

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])
Sign up to request clarification or add additional context in comments.

2 Comments

i never realized lists did this, is this just a numpy array thing?
Yeah, it's numpy
1

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!

3 Comments

This will give the sum of negative values instead of the count.
This is not the way to work with numpy arrays. This will run in python time, but a native numpy approach will run in C time (which could be orders of magnitude faster)
I don't use numpy a lot, so I wanted to test it. Thank you @roganjosh that makes total sense. numpy clearly won.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.