Reputation: 3
I've searched everywhere for an answer to this, sorry if it's a very basic question. I am filtering Numpy arrays using a boolean Numpy array that is created by comparing values at the same indices in 3 different arrays. My comparison is comprised of 2 separate boolean statements, say x[i]==y[i] & x[i]!=z[i], for all indices i. Here's the troubling results:
x[8]=25
y[8]=27
z[8]=13
x[8]==y[8]
False
x[8]!=z[8]
True
x[8]==y[8] & x[8]!=z[8]
True
As you can see, the above False & True returns a True. What am I missing? As another example of my frustration, here's another example from the same arrays that is returning the proper results:
x[3]=24
y[3]=18
z[3]=27
x[3]==y[3]
False
x[3]!=z[3]
True
x[3]==y[3] & x[3]!=z[3]
False
As you can see, this example works fine. Any help would be appreciated.
Thanks!
Upvotes: 0
Views: 45
Reputation: 100
do (x[8]==y[8]) & (x[8]!=z[8]) or even better x[8]==y[8] and x[8]!=z[8]
Upvotes: -1
Reputation: 280788
What am I missing?
You're missing parentheses:
(x[8]==y[8]) & (x[8]!=z[8])
Also, you should be doing this as a vectorized operation over the whole arrays, rather than by looping over indices. Hopefully, you're doing that in your real code, and you just used specific indices here to make the example simpler:
(x == y) & (x != z) # Evaluates to an array of booleans.
&
is the bitwise AND operator, not the logical AND, but since logical and
can't be overloaded for broadcasting (with good reason), NumPy uses &
for logical AND on boolean arrays. &
has different precedence from and
, so you need to parenthesize some operations you wouldn't need to parenthesize with and
.
Upvotes: 1