\(\newcommand{L}[1]{\| #1 \|}\newcommand{VL}[1]{\L{ \vec{#1} }}\newcommand{R}[1]{\operatorname{Re}\,(#1)}\newcommand{I}[1]{\operatorname{Im}\, (#1)}\)
Comparing arrays¶
A comparison between two arrays returns the elementwise result of the comparison:
>>> import numpy as np
>>> arr1 = np.array([[0, 1, 2],
... [3, 4, 5]])
>>> arr2 = np.array([[1, 1, 2],
... [3, 4, 6]])
>>> arr1 == arr2
array([[False, True, True],
[ True, True, False]], dtype=bool)
Sometimes we want to know if two arrays are equal, in the sense that all the
elements of the two arrays are equal to each other. For this we use
np.all
. np.all
accepts an array as input, and returns True if all the
elements are non-zero [1].
>>> np.all([1, 2, 3])
True
Python assumes that True == 1
and False == 0
for this test of
non-zero:
>>> np.all([True, True, True])
True
>>> np.all([1, 2, 0])
False
>>> np.all([True, False, True])
False
To ask whether all the elements in two arrays are equal, we can pass the
result of the element-wise comparison to np.all
:
>>> np.all(arr1 == arr2)
False
>>> arr3 = arr1.copy()
>>> np.all(arr1 == arr3)
True
Sometimes we want to know if any of the values in an array are non-zero
[1]. Enter np.any
:
>>> np.any([False, False, False])
False
>>> np.any([False, False, True])
True
>>> np.any(arr1 == arr2)
True
>>> np.any(arr1 != arr3)
False
Footnotes
[1] | (1, 2) For numerical arrays, testing whether an element is “non-zero”
has the obvious meaning of element != 0 . For boolean arrays non-zero
means element == True . For other array types, non-zero means
bool(element) == True where bool uses the Kind-of True
algorithm to return True or False from an element. |