Search code examples
arraysnumpyparentheses

What does a code np.mean(array_1 == array_2) do?


What does the following code do?

import numpy as np
np.mean(array_1 == array_2)

Here array_1 and array_2 are same shaped arrays of type int.


Solution

  • This gives the average similarity between the two arrays, that is the number of elements that were identical divided by the length of the arrays.

    Note that if the arrays are different lengths, the == will evaluate to False and the returned mean will be 0.0


    >>> import numpy as np
    >>> array_1 = np.arange(4)
    >>> array_2 = np.arange(4) % 3
    >>> array_1
    array([0, 1, 2, 3])
    >>> array_2
    array([0, 1, 2, 0])
    >>> np.mean(array_1 == array_2)
    0.75