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))
Rewned
  • 61
  • 4

3 Answers3

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
timgeb
  • 76,762
  • 20
  • 123
  • 145
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())
Andrea Dusza
  • 2,080
  • 3
  • 18
  • 28
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_
Iman Mirzadeh
  • 12,710
  • 2
  • 40
  • 44