I can do
arr = np.random.randint(0, 1, size=(10,10))
arr == 1
and get a boolean array as an output.
What if my array is an object data type and I want to check that certain elements are an instance of some class? Is there a native way to do it?
Looks like numpy.vectorize is an option that numpy provides for doing so:
>>> np_isinstance = np.vectorize(isinstance)
>>> np_isinstance(arr, str)
array([[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False],
[False, False, False, False, False, False, False, False, False,
False]])
But see this post about efficiency; it is basically doing a for loop, so there aren't the same efficiency benefits of built-in numpy methods. Other options are also discussed on the thread, if you are interested.
intdtype and all values 0. The second line replaces it with a scalar1. I don't see where you get an boolean array. Nor do I seeobjectdtype array.isinstanceof the objects the same way as you would in a list.. Other than allowing things likereshape, object dtype array adds nothing to lists.==not=. I wish people would show the output of their code. I do that all time in my answers. But I don't see the relevance of that to theisinstancequestion. The boolean aray has abooldtype. Checking the arraydtypeis different from checking element class.