简体   繁体   中英

How can I determine the underlying type in a numpy object dtype?

If I have a custom python class, and use that in a numpy.ndarray , my array ends up with dtype 'O' (object), which is fine:

import numpy

class Test(object):
    """Dummy class
    """
    def __init__(self, value):
        self.value = value

    def __float__(self):
        return float(self.value)


arr = numpy.array([], dtype=Test)

This gives me array([], dtype=object) , but how can I unwrap the dtype to check that the underlying type is Test ?

This is easy when there are elements in the array, since I can use isinstance on any of the members, but when the array is empty, I am stumped. I hope that the underlying type is stored in the dtype somewhere...

You can't. Arrays aren't meant to be used with non-primitive types (efficiently), and really are no different from a (terribly slow) list. In fact, once you go object, you can put anything you want into the array:

array((Test(),[])) #works fine, dtype object. Even explicitly setting dtype will not fail, and be ignored.

As you can see - if you do not put a primitive numpy can convert to, no type enforcing is done.

Though I would not recommend an array at all, if you can guarantee the array contains a single type, then

type(arr[0])

is really your only option (which is shape dependent of course).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM