What is the most efficient way to implement matlab's ismember(A, b) in python where in A is any numpy ndarray and b is a list of values. It should return a mask as a boolean ndarray of the same shape as A where in an element is True if the corresponding value in A is in the list of values in b.
I want to replace all elements of A with value in list B with something.
I expected A[A in B] = 0
to work but it throws the following error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
If an implementation of an equivalent of ismember
is there then the following would do what I need:
A[ismember(A, b)] = 0
Note: I don't want solutions involving looping through all elements of A in python.
Based on the answer of ajcr, one solution is:
import numpy as np
def ismember(A, b):
return np.in1d(A, b).reshape(A.shape)
But this is quite slow and runs out of memory. For my case, A is an image as big as 512 x 512 x 1200. b has about 1000 elements.