For example, trying to make sense of these results:
>>> x
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> (x == np.array([[1],[2]])).astype(np.float32)
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)
>>> (x == np.array([1,2]))
False
>>> (x == np.array([[1]])).astype(np.float32)
array([[ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32)
>>> (x == np.array([1])).astype(np.float32)
array([ 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)
>>> (x == np.array([[1,3],[2]]))
False
>>>
What's going on here? In the case of [1], it's comparing 1 to each element of x and aggregating the result in an array. In the case of [[1]], same thing. It's easy to figure out what's going to occur for specific array shapes by just experimenting on the repl. But what are the underlying rules where both sides can have arbitrary shapes?
It's possible that what's confusing you is that:
some broadcasting is going on.
you appear to have an older version of numpy.
is broadcasting. It compares
x
to each of the first and second arrays; as they are scalars, broadcasting implies that it compares each element ofx
to each of the scalars.However, each of
and
can't be broadcast. By me, with
numpy
1.10.4, this givesNumPy tries to broadcast the two arrays to compatible shapes before comparison. If the broadcasting fails, False is currently returned. In the future,
Otherwise, a boolean array resulting from the element-by-element comparison is returned. For example, since
x
andnp.array([1])
are broadcastable, an array of shape (10,) is returned:Since
x
andnp.array([[1,3],[2]])
are not broadcastable,False
is returned byx == np.array([[1,3],[2]])
.