Numpy 修炼之道 (3)—— 数据类型
Numpy 中的数组比
Python 原生中的数组(只支持整数类型与浮点类型)强大的一点就是它支持更多的数据类型。

基本数据类型
Numpy 常见的基本数据类型如下:

  数据类型     描述
   bool_         布尔(True或False),存储为一个字节
   int_           默认整数类型(与C long相同;通常为int64或int32)
   intc           与C int(通常为int32或int64)相同
   intp          用于索引的整数(与C ssize_t相同;通常为int32或int64)
   int8          字节(-128到127)
   int16        整数(-32768到32767)
   int32        整数(-2147483648至2147483647)
   int64       整数(-9223372036854775808至9223372036854775807)

 uint8无符号整数(0到255)
 uint16无符号整数(0到65535)
 uint32 无符号整数(0至4294967295)
 uint64 无符号整数(0至18446744073709551615)
 float_ float64的简写。
 


 
 float16半精度浮点:符号位,5位指数,10位尾数
 


 
 float32单精度浮点:符号位,8位指数,23位尾数
 


 
 float64 双精度浮点:符号位,11位指数,52位尾数
 


 
 complex_complex128的简写。
 


 
 complex64 复数,由两个32位浮点(实数和虚数分量)
 


 
 complex128 复数,由两个64位浮点(实数和虚数分量)
 


以上这些数据类型都可以通过 np.bool_、np.float32等方式访问。
这些类型都可以在创建 ndarray 时通过参数 dtype 来指定。


>>> a = np.arange(3, dtype=np.float16)
>>> a
array([ 0.,  1.,  2.])
>>> a.dtype
dtype('float16')

此外,在创建 ndarray 对象时,也可以通过字符代码来替换,主要是为了保持与较旧包(例如Numeric)的向后兼容性。

>>> np.array([1, 2, 3], dtype='f')
array([ 1.,  2.,  3.], dtype=float32)

但是不推荐使用这种字符代码的方式
类型转换
要转换数组的类型,请使用.astype()方法(首选)或类型本身作为函数。


>>> a
array([ 0.,  1.,  2.])
>>> a.astype(np.bool_)
array([False,  True,  True], dtype=bool)
>>> np.bool_(a)
array([False,  True,  True], dtype=bool)


脑洞科技栈专注于人工智能与量化投资领域
Numpy 修炼之道 (3)—— 数据类型
了解更多干货文章,关注小程序八斗问答


 

相关文章: