简体   繁体   中英

filtering negative values in a numpy array

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 (ie 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM