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?

Alexander Soare
  • 2,825
  • 3
  • 25
  • 53
  • 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. – hpaulj Mar 06 '21 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. – hpaulj Mar 06 '21 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. – hpaulj Mar 07 '21 at 03:20

1 Answers1

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.

Tom
  • 8,310
  • 2
  • 16
  • 36