KKS
KKS

Reputation: 1389

How to check If all elements in a NumPy array are either 0 or 2?

Pseudocode:

if (all elements in c == 0) or (all elements in c == 2):
    # all elements in 'c' are either 0 or 2.
    . . .

If c = numpy.array[0,0,2] the condition is true, but if c = numpy.array[0,1,2] it is false.

How to test this condition in Numpy efficiently?

Upvotes: 3

Views: 3439

Answers (4)

MinYoung Kim
MinYoung Kim

Reputation: 139

quick visual test is doing

np.unique(arr1)

This lists all the unique elements in arr1. So if you get anything that doens't contain only 0 or 2 you can visually know immediately. Just a tip.

Upvotes: 0

tstanisl
tstanisl

Reputation: 14107

You could use binary operators as logical ones:

((x == 0) | (x == 2)).all()

This is slightly faster (~20-30%) than "np.isin" solution.

Upvotes: 6

Chris
Chris

Reputation: 29732

numpy.isin is designed for this:

import numpy as np

arr1 = np.array([0, 0, 2])
arr2 = np.array([0, 1, 2])

np.isin(arr1, [0, 2]).all()
# True

np.isin(arr2, [0, 2]).all()
# False

This, of course, works regardless of ndim:

arr3 = np.random.randint(0, 3, (100, 100))
arr4 = np.random.choice([0,2], (100, 100))

np.isin(arr3, [0, 2]).all()
# False

np.isin(arr4, [0, 2]).all()
# True

Upvotes: 13

Narasimha Prasanna HN
Narasimha Prasanna HN

Reputation: 662

Simple method : Just count the number of 0s and 2s , check if it's count is equal to length of array:

def check(array):
   return array.count(0) + array.count(2) == len(array) 

Upvotes: 4

Related Questions