如果我有一个 numpy dtype,我如何自动将其转换为最接近的 python 数据类型?例如,
numpy.float32 -> "python float"
numpy.float64 -> "python float"
numpy.uint32 -> "python int"
numpy.int16 -> "python int"
我可以尝试提出所有这些情况的映射,但是 numpy 是否提供了某种自动方式将其 dtype 转换为最接近的可能的 native python 类型?这种映射不需要详尽,但它应该转换具有接近 python 模拟的常见 dtype。我认为这已经发生在 numpy 的某个地方。
最佳答案
使用 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 array scalars 的转换表对于您的系统:
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 等效项。
https://stackoverflow.com/questions/9452775/