如果我有一个numpy dtype,我如何自动将其转换为最接近的python数据类型?例如,
numpy.float32 -> "python float"
numpy.float64 -> "python float"
numpy.uint32 -> "python int"
numpy.int16 -> "python int"
我可以尝试提出所有这些情况的映射,但是numpy是否提供了一些自动的方法来将其dtypes转换为尽可能接近的本机python类型?这种映射不需要是详尽的,但它应该转换具有类似python的常见dtype。我想这已经在numpy的某个地方发生了。
numpy将该信息保存在一个暴露为typeDict的映射中,因此您可以执行如下操作:
>>> import __builtin__ as builtins # if python2
>>> import builtins # if python3
然后::
>>> import numpy as np
>>> {v: k for k, v in np.typeDict.items() if k in dir(builtins)}
{numpy.object_: 'object',
numpy.bool_: 'bool',
numpy.string_: 'str',
numpy.unicode_: 'unicode',
numpy.int64: 'int',
numpy.float64: 'float',
numpy.complex128: 'complex'}
如果你想要实际的python类型,而不是它们的名称,你可以执行::
>>> {v: getattr(builtins, k) for k, v in np.typeDict.items() if k in vars(builtins)}
{numpy.object_: object,
numpy.bool_: bool,
numpy.string_: str,
numpy.unicode_: unicode,
numpy.int64: int,
numpy.float64: float,
numpy.complex128: complex}
numpy将该信息保存在一个暴露为typeDict的映射中,因此您可以执行如下操作:
>>> import __builtin__ as builtins # if python2
>>> import builtins # if python3
然后::
>>> import numpy as np
>>> {v: k for k, v in np.typeDict.items() if k in dir(builtins)}
{numpy.object_: 'object',
numpy.bool_: 'bool',
numpy.string_: 'str',
numpy.unicode_: 'unicode',
numpy.int64: 'int',
numpy.float64: 'float',
numpy.complex128: 'complex'}
如果你想要实际的python类型,而不是它们的名称,你可以执行::
>>> {v: getattr(builtins, k) for k, v in np.typeDict.items() if k in vars(builtins)}
{numpy.object_: object,
numpy.bool_: bool,
numpy.string_: str,
numpy.unicode_: unicode,
numpy.int64: int,
numpy.float64: float,
numpy.complex128: complex}
对于那些不需要自动转换并且知道值的numpy dtype的人来说,关于数组标量的一个旁注:
Array scalars differ from Python scalars, but for the most part they can be used interchangeably (the primary exception is for versions of Python older than v2.x, where integer array scalars cannot act as indices for lists and tuples). There are some exceptions, such as when code requires very specific attributes of a scalar or when it checks specifically whether a value is a Python scalar. Generally, problems are easily fixed by explicitly converting array scalars to Python scalars, using the corresponding Python type function (e.g., int, float, complex, str, unicode).
源
因此,在大多数情况下,可能根本不需要转换,可以直接使用数组标量。效果应该与使用Python scalar相同:
>>> np.issubdtype(np.int64, int)
True
>>> np.int64(0) == 0
True
>>> np.issubdtype(np.float64, float)
True
>>> np.float64(1.1) == 1.1
True
但是,如果出于某种原因,需要显式转换,则使用相应的Python内置函数是正确的方法。正如另一个答案所示,它也比数组标量item()方法快。
使用val.item()将大多数NumPy值转换为原生Python类型:
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 'int'>
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以来已弃用)。
对于好奇的人来说,为您的系统构建一个NumPy数组标量转换表:
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等效值。