Fidel - 7 months ago 94

Python Question

I have already checked this thread How to count values in a certain range in a Numpy array? but their answer does not seem to work.

I have a numpy array of 2000 floats called data:

`print(type(data)) --> <type 'list'>`

print(type(data[0])) --> <type 'numpy.float64'>

And I have 2 variables to form a range, minV and maxV:

`print(type(minV)) --> <type 'float'>`

print(type(maxV)) --> <type 'float'>

If I try the solution given in the link mentioned above, I receive this exception:

`((minV < data) & (data < maxV)).sum()`

AttributeError: 'bool' object has no attribute 'sum'

And indeed, that expression is a boolean:

`print(type( (minV < data) & (data < minV) ) ) --> <type 'bool'>`

print( ( (minV < data) & (data < minV) ) ) --> True

The python version I am using is Python 2.7.3 -- EPD 7.3-2 (64-bit)

Numpy version is 1.6.1

System is Linux (Although I ignore if that is important).

Thanks.

Answer

I suspect you are using python 2 because comparing a list and a number doesn't raise a `TypeError`

in your case.

But in order to use element-wise comparison (`<`

, `>`

, `&`

) you need to convert your list to a numpy array:

```
import numpy as np
data = np.array(data)
((minV < data) & (data < maxV)).sum()
```

should work. For example:

```
data = list(range(1000))
minV = 100
maxV = 500
data = np.array(data)
((minV < data) & (data < maxV)).sum() # returns 399
```