If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example,
numpy.float32 -> "python float"
numpy.float64 -> "python float"
numpy.uint32 -> "python int"
numpy.int16 -> "python int"
I could try to come up with a mapping of all of these cases, but does numpy provide some automatic way of converting its dtypes into the closest possible native python types? This mapping need not be exhaustive, but it should convert the common dtypes that have a close python analog. I think this already happens somewhere in numpy.
How about:
Use either
a.item()
ornp.asscalar(a)
to convert most NumPy values to a native Python type:Read more in the NumPy manual. For the curious, to build a table of conversions for your system:
There are a few NumPy types that have no native Python equivalent on some systems, including:
clongdouble
,clongfloat
,complex192
,complex256
,float128
,longcomplex
,longdouble
andlongfloat
. These need to be converted to their nearest NumPy equivalent before usingasscalar
.tolist()
is a more general approach to accomplish this. It works in any primitive dtype and also in arrays or matrices.I doesn't actually yields a list if called from primitive types:
numpy == 1.15.2
You can also call the
item()
method of the object you want to convert:numpy holds that information in a mapping exposed as
typeDict
so you could do something like the below::If you want the actual python types rather than their names, you can do ::
I think you can just write general type convert function like so:
This means there is no fixed lists and your code will scale with more types.