3

I am new to python and created a small function that does a cluster analysis. The quick rundown is I have to compare two arrays a multitude of times, until it no longer changes. For that I have used a while loop, that loops as long as they are not equal, but I find that I get two different results from != and not ==. MWE:

import numpy as np

a = np.array([1,1,1])
b = np.array([1,2,1])

print((a != b).all())
print(not (a == b))
1
  • 5
    In your example, did you mean to write not (a == b).all()? Commented Jan 1, 2016 at 20:55

3 Answers 3

1

not (a == b) will raise a ValueError because the truth-value of an array with multiple elements is ambiguous.

The way you invert a boolean array in numpy is with the ~ operator:

>>> a != b
array([False,  True, False], dtype=bool)
>>> ~ (a == b)
array([False,  True, False], dtype=bool)
>>> (~ (a == b)).all() == (a != b).all()
True
Sign up to request clarification or add additional context in comments.

Comments

1

The following two expressions are equal. They return true when there is at least one different element.

print((a != b).any())
print(not (a == b).all())

And the following two also give the same result. They return true when every element in the same position is different in the two arrays.

print((a != b).all())
print(not (a == b).any())

Comments

0

to understand more, look at this code , you want to compare d and c but both are arrays so you should compare correctly not by just not operator!!

a = np.array([1,1,1])
b = np.array([1,2,1])
c = (a!=b)
type(c)
Out[6]: numpy.ndarray
type(a)
Out[7]: numpy.ndarray
c
Out[8]: array([False,  True, False], dtype=bool)
c.all()
Out[9]: False
d = (a==b)
type(d)
Out[11]: numpy.ndarray
d
Out[12]: array([ True, False,  True], dtype=bool)
not d
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-84cd3b926fb6> in <module>()
----> 1 not d

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

not(d.any())
Out[15]: False

x = d.any()
type(x)
Out[19]: numpy.bool_

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.