How do I access and modify Python arrays using boolean operators?

I would like to know how to execute the following MATLAB statement in Python:

X(0.80 < X & X < 1) = 1;

      

The statement says Put 1 in the indices where the value of X is between 0.8 and 1

.

I'm looking for a solution in NumPy arrays of Python lists.

Thank.

I tried:

X[X > 0.8 and X < 1]

      

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

+3


source to share


1 answer


This is an order-of-work issue, so use parentheses:

X[(X > 0.8) & (X < 1)]

      



Note that I am also using ampersand instead of and

.

+6


source







All Articles