参考文章:https://www.numpy.org.cn/user_guide/numpy_basics/data_types.html
Numpy支持很多种数据类型,部分常用类型见下表
数据类型 | 描述 |
---|---|
bool_ | 布尔(True或False),存储为一个字节 |
int_ | 默认整数类型(与Clong相同;通常是int64或int32 |
INTC | 与Cint(通常为int32或int64)相同 |
INTP | 用于索引的整数(与Cssize_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等方式访问。
数据类型可以用作函数将python数字转换为数组标量(有关说明,请参阅数组标量部分)、将python数字序列转换为该类型的数组、或作为许多numpy函数或方法接受的dtype关键字参数。一些例子:
>>> import numpy as np
>>> x = np.float32(1.0)
>>> x
1.0
>>> y = np.int_([1,2,4])
>>> y
array([1, 2, 4])
>>> z = np.arange(3, dtype=np.uint8)
>>> z
array([0, 1, 2], dtype=uint8)
数组类型也可以由数据协议类型字符串代替,通常由两个字符组成,第一个字符代表类型,第二个字符代表类型所占字节。以下是规定的代表类型的字符。
字符 | 代表类型 |
---|---|
‘?’ | boolean |
‘b’ | (signed) byte |
‘B’ | unsigned byte |
‘i’ | (signed) integer |
‘u’ | unsigned integer |
‘f’ | floating-point |
‘c’ | complex-floating point |
‘m’ | timedelta |
‘M’ | datetime |
‘O’ | (Python) objects |
‘S’, ‘a’ | zero-terminated bytes (not recommended) |
‘U’ | Unicode string |
‘V’ | raw data (void) |
下面是一些例子
>>> dt = np.dtype('i4') # 32-bit signed integer
>>> dt = np.dtype('f8') # 64-bit floating-point number
>>> dt = np.dtype('c16') # 128-bit complex floating-point number
>>> dt = np.dtype('a25') # 25-length zero-terminated bytes
>>> dt = np.dtype('U25') # 25-character string
但实际上我们推荐使用dtype对象表示类型,因为其表达的意思更加清楚。