0

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?

3
  • The first line makes a (10,10) array of int dtype and all values 0. The second line replaces it with a scalar 1. I don't see where you get an boolean array. Nor do I see object dtype array. Commented Mar 6, 2021 at 17:23
  • For an object dtype array, you check the isinstance of the objects the same way as you would in a list.. Other than allowing things like reshape, object dtype array adds nothing to lists. Commented Mar 6, 2021 at 17:41
  • Oops, I see that you used == 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 the isinstance question. The boolean aray has a bool dtype. Checking the array dtype is different from checking element class. Commented Mar 7, 2021 at 3:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for that and the heads up. Will leave it open for a bit before marking as answered

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.