使用^{}将大多数NumPy值转换为本机Python类型:import numpy as np
# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval)) #
# and similar...
type(np.float64(0).item()) #
type(np.uint32(0).item()) #
type(np.int16(0).item()) #
type(np.cfloat(0).item()) #
type(np.datetime64(0, 'D').item()) #
type(np.datetime64('2001-01-01 00:00:00').item()) #
type(np.timedelta64(0, 'D').item()) #
...
(另一个方法是^{},但是自从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等价物。