Numpy系列(二)- 数据类型
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
Out[107]: array([0., 1., 2.], dtype=float16)
a.dtype
Out[108]: dtype('float16')
此外,在创建 ndarray 对象时,也可以通过字符代码来替换,主要是为了保持与较旧包(例如Numeric)的向后兼容性。
np.array([1, 2, 3], dtype='f') Out[109]: array([1., 2., 3.], dtype=float32
类型转换
要转换数组的类型,请使用.astype()方法(首选)或类型本身作为函数。
a Out[110]: array([0., 1., 2.], dtype=float16) a.astype(np.bool_) Out[111]: array([False, True, True]) np.bool_(a) Out[112]: array([False, True, True])

浙公网安备 33010602011771号