Reputation: 317
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!
Upvotes: 4
Views: 4123
Reputation: 68682
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)
Upvotes: 3
Reputation: 76745
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)
Upvotes: 1
Reputation: 68
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?
Upvotes: -1