3

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?

1
  • Ok. my question should be more clear. the array is a numpy array. Commented Jul 29, 2019 at 7:40

4 Answers 4

13

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
Sign up to request clarification or add additional context in comments.

Comments

6

You could use binary operators as logical ones:

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

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

Comments

4

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) 

1 Comment

This works for Normal arrays, if you are sticking to numpy use the solution provided by @Chris
0

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.

1 Comment

computing unique() requires sorting whole arr1, thus it will be significantly slower than other solutions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.