0. numpy 下的数据类型
- uint:
- np.uint, np.uint0, np.uint8, np.uint16, np.uint32, np.uint64
- int:
- np.int, np.int0, np.int8, np.int16, np.int32, np.int64
- float
- x.astype(‘float32’) 等价于 x.astype(np.float32)
- np.float, np.float16, np.float32, np.float64
1. 查看 numpy 数据类型和 Python 原生数据类型之间的对应关系
In [51]: dict([(d, type(np.zeros(1,d).tolist()[0])) for d in
(np.float32, np.float64, np.uint32, np.int16)])
Out[51]:
{numpy.float32: float,
numpy.int16: int,
numpy.uint32: int,
numpy.float64: float}
2. 使用 np.asscalar(a) 或 a.item() 进行转化
Converting numpy dtypes to native python types
这两种方式仅可转化单个数值,而不可对 numpy 下的多维数组进行转化。
import numpy as np
# examples using a.item()
type(np.float32(0).item()) # <type 'float'>
type(np.float64(0).item()) # <type 'float'>
type(np.uint32(0).item()) # <type 'long'>
# examples using np.asscalar(a)
type(np.asscalar(np.int16(0))) # <type 'int'>
type(np.asscalar(np.cfloat(0))) # <type 'complex'>
type(np.asscalar(np.datetime64(0))) # <type 'datetime.datetime'>
type(np.asscalar(np.timedelta64(0))) # <type 'datetime.timedelta'>
...