How to define numpy types in python?

How can one reliably determine if an object is of type numpy?

I understand that this question runs counter to the duck printing philosophy, but the idea is to make sure that a function (which uses scipy and numpy) never returns a numpy type unless called with a numpy type. This arises in solving another question , but I think that the general problem of determining whether an object is of type numpy is far enough from this original question that they should be separated.

+65
python numpy duck-typing dynamic-typing
Sep 24
source share
6 answers

Use the built-in type function to get the type, then you can use the __module__ property to find out where it was defined:

 >>> import numpy as np a = np.array([1, 2, 3]) >>> type(a) <type 'numpy.ndarray'> >>> type(a).__module__ 'numpy' >>> type(a).__module__ == np.__name__ True 
+75
Sep 24 '12 at 17:36
source share

The solution I came up with is:

 isinstance(y, (np.ndarray, np.generic) ) 

However, it is not 100% clear that all numpy types are guaranteed to be np.ndarray or np.generic , and this probably isn’t a reliable version.

+44
Sep 24
source share

Old question, but I came up with a definitive answer with an example. It doesn’t hurt to keep questions fresh, as I had the same problem and I couldn’t find a clear answer. The key is to make sure you import numpy and then run the isinstance bool. Although this may seem simple if you are doing some calculations on different types of data, this little check can serve as a quick test before starting any operation with a zero vector.

 ################## # important part! ################## import numpy as np #################### # toy array for demo #################### arr = np.asarray(range(1,100,2)) ######################## # The instance check ######################## isinstance(arr,np.ndarray) 
+16
Oct 16 '16 at 2:30
source share

To get a type, use the built-in type function. Using the in operator, you can check if a type is a numpy type by checking if it contains a numpy string;

 In [1]: import numpy as np In [2]: a = np.array([1, 2, 3]) In [3]: type(a) Out[3]: <type 'numpy.ndarray'> In [4]: 'numpy' in str(type(a)) Out[4]: True 

(This example was run in IPython , very convenient for interactive use and quick tests.)

+8
Sep 24 '12 at 17:04
source share

It depends on what you are looking for.

  • If you want to check if the sequence is ndarray , then isinstance(..., np.ndarray) is probably the easiest. Make sure you do not restart numpy in the background, as the module may be different, but otherwise you should be fine. MaskedArrays , matrix , recarray are all subclasses of ndarray , so you should be set.
  • If you want to check if a scalar is a numeric scalar, things get a little more complicated. You can check if it has the shape and dtype . You can compare its dtype with the basic dtypes, a list of which you can find in np.core.numerictypes.genericTypeRank . Note that the items in this list are strings, so you will need to do tested.dtype is np.dtype(an_element_of_the_list) ...
+7
Sep 24 '12 at 18:20
source share

Note that type(numpy.ndarray) is type itself and watch out for boolean and scalar types. Do not be discouraged if it is not intuitive or simple, it is pain at first.

See also: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.dtypes.html - https://github.com/machinalis/mypy-data/tree/master/numpy- mypy

 >>> import numpy as np >>> np.ndarray <class 'numpy.ndarray'> >>> type(np.ndarray) <class 'type'> >>> a = np.linspace(1,25) >>> type(a) <class 'numpy.ndarray'> >>> type(a) == type(np.ndarray) False >>> type(a) == np.ndarray True >>> isinstance(a, np.ndarray) True 

Fun with logical values:

 >>> b = a.astype('int32') == 11 >>> b[0] False >>> isinstance(b[0], bool) False >>> isinstance(b[0], np.bool) False >>> isinstance(b[0], np.bool_) True >>> isinstance(b[0], np.bool8) True >>> b[0].dtype == np.bool True >>> b[0].dtype == bool # python equivalent True 

See more fun with scalar types: - https://docs.scipy.org/doc/numpy-1.15.1/reference/arrays.scalars.html#arrays-scalars-built-in

 >>> x = np.array([1,], dtype=np.uint64) >>> x[0].dtype dtype('uint64') >>> isinstance(x[0], np.uint64) True >>> isinstance(x[0], np.integer) True # generic integer >>> isinstance(x[0], int) False # but not a python int in this case # Try matching the 'kind' strings, eg >>> np.dtype('bool').kind 'b' >>> np.dtype('int64').kind 'i' >>> np.dtype('float').kind 'f' >>> np.dtype('half').kind 'f' # But be weary of matching dtypes >>> np.integer <class 'numpy.integer'> >>> np.dtype(np.integer) dtype('int64') >>> x[0].dtype == np.dtype(np.integer) False # Down these paths there be dragons: # the .dtype attribute returns a kind of dtype, not a specific dtype >>> isinstance(x[0].dtype, np.dtype) True >>> isinstance(x[0].dtype, np.uint64) False >>> isinstance(x[0].dtype, np.dtype(np.uint64)) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: isinstance() arg 2 must be a type or tuple of types # yea, don't go there >>> isinstance(x[0].dtype, np.int_) False # again, confusing the .dtype with a specific dtype # Inequalities can be tricky, although they might # work sometimes, try to avoid these idioms: >>> x[0].dtype <= np.dtype(np.uint64) True >>> x[0].dtype <= np.dtype(np.float) True >>> x[0].dtype <= np.dtype(np.half) False # just when things were going well >>> x[0].dtype <= np.dtype(np.float16) False # oh boy >>> x[0].dtype == np.int False # ya, no luck here either >>> x[0].dtype == np.int_ False # or here >>> x[0].dtype == np.uint64 True # have to end on a good note! 
+1
Feb 01 '19 at 2:16
source share



All Articles