Reputation: 91
I have one vector called cm which does not change
cm = np.array([[99,99,0]])
and another vector called pt. that I want to loop through certain values. but when the two are equal, I want it skip over and not perform the operation. for the sake of this post I just said to have it print out the value of pt, but I actually have a whole host of operations to run. here is my code
for i in range (95,103):
for j in range (95,103):
pt = np.array([[i,j,0]])
if pt == cm:
continue
print pt
i have tried changing the 4th line to
if pt.all == cm.all
but that prints everything, including the one I want to skip and then if i turn it into
if pt.all() == cm.all()
that also doesn't work. what is the difference between those two anyway?
does anyone know how i can fix it so that when pt = [99,99,0] it will skip the operations and go back to the beginning of the loop? Thanks!
Upvotes: 5
Views: 12697
Reputation: 353019
You're probably looking for (pt == cm).all()
, although if floats are involved np.allclose(pt, cm)
is probably a better idea in case you have numerical errors.
(1) pt.all == cm.all
This checks to see whether the two methods are equal:
>>> pt.all
<built-in method all of numpy.ndarray object at 0x16cbbe0>
>>> pt.all == cm.all
False
(2) pt.all() == cm.all()
This checks to see see whether the result of all
matches in each case. For example:
>>> pt
array([[99, 99, 0]])
>>> pt.all()
False
>>> cm = np.array([10, 10, 0])
>>> cm.all()
False
>>> pt.all() == cm.all()
True
(3) (pt == cm).all()
This creates an array testing to see whether the two are equal, and returns whether the result is all True:
>>> pt
array([[99, 99, 0]])
>>> cm
array([[99, 99, 0]])
>>> pt == cm
array([[ True, True, True]], dtype=bool)
>>> (pt == cm).all()
True
One downside is that this constructs a temporary array, but often that's not an issue in practice.
Aside: when you're writing nested loops with numpy arrays you've usually made a mistake somewhere. Python-level loops are slow, and so you lose a lot of the benefits you get from using numpy
in the first place. But that's a separate issue.
Upvotes: 6