Search code examples
pythonnumpyvalueerror

How can I find the indices of values in a Numpy array that are between two threshold values?


I have a Numpy array result.pvalues, representing statistical p-values. I want to find the indices of p-values that are between 0.01 and 0.05.

I was able to find indices for p-values less than 0.05 like so:

print(np.where(result.pvalues < 0.05)[0])

But if I try to add the other condition like so:

print(np.where(result.pvalues < 0.05 and result.pvalues >= 0.01)[0])

I get an error that says:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Why does this error occur, and what does the message mean?

As far as I know, a.any() and a.all() determine if any (respectively all) elements of a are True. But I don't want that, I want to get an array of boolean results (to use np.where on them).


Solution

  • For arrays you need to use numpy.logical_and. This should work:

    print(np.where(np.logical_and(result.pvalues < 0.05, result.pvalues >= 0.01))[0])