在
NumPy
中常常需要确定元素的数据类型,而在使用过程中能够发现全称和缩写都能满足要求,但是对于数据类型全称和缩写及其对应的数据类型和存储空间的描述在各种笔记中还是不够全面,因此本文对
NumPy
数据类型进行了较为系统总结,望批评指正一同进步!
01
全称里的“
_
”
在使用时发现有些全称后面有“
_
”有些就没有,以
np.unicode_
为例:
np.unicode
和
np.unicode_
实际上是相同的数据类型,都表示
Unicode
字符串。但是在
NumPy
中,数据类型名称后面的下划线是为了避免与
Python
内置类型的名称冲突。
通常在以字母结尾的数据类型全称之后需要加上下划线与内置类型相区分
02
全称缩写对照表
全称 | 缩写 | 注释 |
np.bool_ | ‘?’, ‘b1’ | 布尔类型 |
np.int8 | ‘b’, ‘i1’ | 8位有符号整数,取值范围为-128~127 |
np.uint8 | ‘B’, ‘u1’ |
|
np.int16 | ‘h’, ‘i2' | |
np.uint16 | ‘H’, ‘u2’ | |
np.int32 | ‘i’, ‘i4' | |
np.uint32 | ‘I’, ‘u4’ | |
np.int64 | ‘q’, ‘i8 | |
np.uint64 | ‘Q’, ‘u8’ | |
np.float16 | ‘f2’, ‘e’ | |
np.float32 | ‘f4’, ‘f’ | |
np.float64 | ‘f8’, ‘d’ | |
np.complex64 | np.c64 | 64位复数,由 |
np.complex128 | np.c128 | 128位复数,由 |
np.str_ | ‘U’ |
|
np.unicode_ | ||
| ‘S’ | 字节类型,以空字符结尾的字节串(NTBS),只能是ASCII码表中有的字符 |
| ||
可以在缩写后添加数字限定长度,如‘U3’表示长度为三的字符串;不写或者采用全称进行表示则是最大长度。 |
03
程序实例
程序:
import numpy as np
a = np.array([1,0,1], dtype=np.bool_)
b = np.array([1,2,3,4,5], dtype = np.int8)
# b = np.array([1,2,3,4,5], dtype = 'i1')
c = np.array([1,2,3,4,5], dtype = np.complex64)
# c = np.array([1,2,3,4,5], dtype = np.c64)
d = np.array(['4','as','👉', 4], dtype = np.str_)
# d = np.array(['4','as','👉', 4], dtype = np.unicode_)
# d = np.array(['4','as','👉', 4], dtype = 'U')
e = np.array(['4','a', 4], dtype = np.string_)
# e = np.array(['4','a', 4], dtype = np.bytes_)
# e = np.array(['4','a', 4], dtype = 'S')
print(a, ';每个元素的字节长度:', a.itemsize, '字节;数据类型:', type(a[0]))
print(b, ';每个元素的字节长度:', b.itemsize, '字节;数据类型:', type(b[0]))
print(c, ';每个元素的字节长度:', c.itemsize, '字节;数据类型:', type(c[0]))
print(d, ';每个元素的字节长度:', d.itemsize, '字节;数据类型:', type(d[0]))
print(e, ';每个元素的字节长度:', e.itemsize, '字节;数据类型:', type(e[0]))
输出:
补充:
对于字节类型的字符(
np.bytes_
),
Python
在输出时常常带有前缀
b ' ****'
,但是这也与安装的
Python
版本有关,以上是
Python3.9