Many numpy functions take dtype arguments as either strings (like "float64"
) or numpy datatypes (like numpy.float64
) or even python datatypes (like float
).
I need to compare two datatypes and want to support this flexible interface. Is there a function under which all of these are forms are equivalent? I.e. I want the minimal function f
such that
f("float64") == f(numpy.float64) == f(float)
What does numpy use internally?
The numpy. char module provides a set of vectorized string operations for arrays of type numpy.
Numpy is generally quite fast, but is not optimized for everything. Read the docs. If there's more than one way of doing things (and there usually is), odds are one way is better for what you're trying to do.
Creating numpy array by using an array function array(). This function takes argument dtype that allows us to define the expected data type of the array elements: Example 1: Python3.
To compare each element of a NumPy array arr against the scalar x using any of the greater (>), greater equal (>=), smaller (<), smaller equal (<=), or equal (==) operators, use the broadcasting feature with the array as one operand and the scalar as another operand.
You should read the Scalars page of the numpy documentation, which describes the data type hierarchy.
For comparing dtypes themselves, you can use np.issubdtype. Some examples:
>>> import numpy as np
>>> np.issubdtype(np.int32, int)
True
>>> np.issubdtype(np.int32, float)
False
>>> np.issubdtype(float, np.floating)
True
>>> np.issubdtype(float, np.inexact)
True
>>> np.issubdtype(np.float32, float)
True
>>> np.issubdtype(np.float32, int)
False
>>> np.issubdtype(np.float32, np.floating)
True
The easiest way to do it would be to create a new numpy.dtype
object each time, as it has all the necessary type normalization/standardization and equality-checking already built in. Actually, I haven't taken a look at the internals, so it's possible that it doesn't actually create a new instance of dtype
for ones that numpy
already has (like how using numpy.array
doesn't always create a new array), which would be nicely efficient.
numpy.float64 == numpy.dtype('float64') == numpy.dtype(numpy.float64) == numpy.dtype(float)
numpy.int32 == numpy.dtype('int32') == numpy.dtype(numpy.int32) == numpy.dtype(int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With