简体   繁体   中英

Want to count the number of values in a column that meet a condition

I am trying to count the number of values in a column that meet a certain condition (for example, are greater than 0.75). The column I have is made up of 2000+ decimals.

This is what I have tried,

a = len(fs)
c = np.zeros(a)

for i in fs[0:a]:
    if i >= 0.75:
        print = 1

    elif i < 0.75:
        print = 0 

fs is my column.

This code correctly prints the 0's and 1's I want, but I am unsure of how to count the number of 1's printed. I thought to first make an array of zeros, then somehow append the array in the loop to have an array of the correct 0's and 1's. Then I could just sum the array. I am not quite sure how to go about this and everything I try is not working (I am pretty inexperienced in programming). Does anyone have any advice about how to go about this? I know this is pretty simple...

Thank you!

In numpy you could do something like:

np.where(fs >= 0.75)[0].size

or

np.count_nonzero(fs >= 0.75)

Both are equivalent, but I probably prefer the second. See the docs for an explanation:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.count_nonzero.html

but basically fs >= 0.75 creates a boolean array of the same length of fs where its elements are True or False based on the conditional. Since this is equivalent to 1 and 0 respectively, np.count_nonzero then returns a count of the non zero elements.

You can, of course, slice fs as well:

np.count_nonzero(fs[0:a] >= 0.75)

It is not clear if you want to compute the number of 1 in the same loop, in which case vaggelas answer is correct.

If you want a separate loop to count the number of values >= 0.75 , you can use:

>>> sum(1 for i in fs[0:a] if i >= 0.75)

If i understand correctly

you can use

countone = 0  #counter for the times you print one
countzero = 0 # counter fot the times you print 0

for i in fs[0:a]:
    if i >= 0.75:
        print = 1
        countone+=1

    elif i < 0.75:
        print = 0 
        countzero +=1

that's what you meant?

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