问题描述
如果我有numpy dtype,如何将其自动转换为最接近的python数据类型?例如,
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"
我可以尝试提出所有这些情况的映射,但是numpy是否提供了一些自动方式将其dtypes转换为最可能的本机python类型?该映射不必详尽无遗,但它应该转换具有类似python类似物的通用dtypes.我认为这已经发生在numpy的某个地方.
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.
推荐答案
使用 val.item()
会将大多数NumPy值转换为原生Python类型:
Use val.item()
to convert most NumPy values to a native Python type:
import numpy as np
# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval)) # <class 'float'>
# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item()) # <class 'long'>
type(np.int16(0).item()) # <class 'int'>
type(np.cfloat(0).item()) # <class 'complex'>
type(np.datetime64(0, 'D').item()) # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item()) # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...
(另一种方法是 np.asscalar(val)
,但是自NumPy 1.16起已弃用.
(Another method is np.asscalar(val)
, however it is deprecated since NumPy 1.16).
出于好奇,构建 NumPy数组标量的转换表用于您的系统:
For the curious, to build a table of conversions of NumPy array scalars for your system:
for name in dir(np):
obj = getattr(np, name)
if hasattr(obj, 'dtype'):
try:
if 'time' in name:
npn = obj(0, 'D')
else:
npn = obj(0)
nat = npn.item()
print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
except:
pass
在某些系统上,有一些NumPy类型没有本地Python等效项,包括:clongdouble
,clongfloat
,complex192
,complex256
,float128
,longcomplex
,longdouble
和longfloat
.在使用.item()
之前,需要将它们转换为最接近的NumPy等效项.
There are a few NumPy types that have no native Python equivalent on some systems, including: clongdouble
, clongfloat
, complex192
, complex256
, float128
, longcomplex
, longdouble
and longfloat
. These need to be converted to their nearest NumPy equivalent before using .item()
.
这篇关于将numpy dtypes转换为本机python类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!