0

I'm trying to calculate the total number of values above 1.6 in my list of 10,000 numbers. I've tried a few ways:

for value in chi_sq_values:
    if value > 1.6:
        print(len(value))

gives me the error in my title but the following works

greater = [i for i in chi_sq_values if i > 1.6]
total = len(greater)
print(total)

I want to try two methods to see validate my answer, how can i fix the first one so it works?

Meems
  • 91
  • 1
  • 7
  • In the first one you are not counting anything. You could do ```np.count_nonzero(chi_sq_values > 1.6)``` to get the count. – Kevin Apr 01 '21 at 14:18
  • Does this answer your question? [What is a good way to do countif in Python](https://stackoverflow.com/questions/2643850/what-is-a-good-way-to-do-countif-in-python) – Fred Larson Apr 01 '21 at 14:30

3 Answers3

3

In your first example, you iterate the items of the list and access directly the value. However, the item doesn't have `len()'. You need to generate the list on your own, in order to evaluate the length.

chi_sq_values = [1, 2, 3]
greater = []
for value in chi_sq_values:
    if value > 1.6:
        print(value)
        greater.append(value)

print(len(greater))
    
zanseb
  • 1,275
  • 10
  • 20
2

In the first code snippet, you try printing the len of value. As numpy.float64 has no len, you get an error.

Therefore, in order to count all values bigger then 1.6, you can simply use a counter:

counter = 0
for value in chi_sq_values:
    if value > 1.6:
        counter += 1
print(counter)
0

The error means that an you cannot call len on numpy.float64 object so you need to do this different way.

Assuming that chi_sq_values is plain list, here's how to do it fast

np.count_nonzero(np.asarray(chi_sq_values) > 1.6)
magma
  • 180
  • 2
  • 6