user308827
user308827

Reputation: 21961

Check if all elements in numpy array match a number

In my python testing script, I want to assert if all elements of numpy array are either very close to 1.0 or equal to 0.0. The array looks like this:

[[0.9999999991268851 1.0000000223517418 0.999999986961484 ...,
  0.9999999841675162 1.0000000074505806 0.9999999841675162]
 [0.9999999991268851 1.0000000223517418 0.999999986961484 ...,
  0.9999999841675162 1.0000000074505806 0.9999999841675162]
 [0.9999999991268851 1.0000000223517418 0.999999986961484 ...,
  0.9999999841675162 1.0000000074505806 0.9999999841675162]
 ..., 
 [1.0000000198488124 1.0000000074505806 1.000000002568413 ...,
  0.9999999888241291 0.9999999925494194 0.0]
 [1.000000011001248 0.9999999850988388 0.9999999869323801 ...,
  1.0000000186264515 0.9999999925494194 0.0]
 [1.000000011001248 0.9999999850988388 0.9999999869323801 ...,
  1.0000000186264515 0.9999999925494194 0.0]]

I thought of using numpy.allclose or numpy.array_equal, but neither makes sense here. ideally, the function should be able to be used in a testing scenario

Upvotes: 1

Views: 1243

Answers (2)

mgilson
mgilson

Reputation: 309821

You can get the 0 elements and mask them out using boolean indexing. Once that's done, np.allclose is exactly what you want:

zeros = arr == 0.0
without_zeros = arr[~zeros]
np.allclose(without_zeros, 1, ...)

Upvotes: 3

forkrul
forkrul

Reputation: 524

The simplest thing I can think of would just be to iterate over every element of the array and test if it is either close to one or equal to zero:

import numpy as np

arr = np.array([[0.9999999991268851, 1.0000000223517418, 0.999999986961484],
                [1.0000000186264515, 0.9999999925494194, 0.0]])

def is_one_or_zero(arr):
  for elem in np.nditer(arr):
    if not (elem == 0 or np.isclose(1.0, elem)):
      return False
  return True

print is_one_or_zero(arr) # Should be True
arr[0, 0] = 1.01
print is_one_or_zero(arr) # Should be False

Upvotes: 0

Related Questions