NumPy-ndarray 的数据类型

ndarray 的数据类型

数据类型,即 dtype ,也是一个特殊的对象, 它包含了ndarray需要为某一种类型数据所申明的内存块信息(也成为了元数据,即表示数据的数据)

dtype是NumPy能够与琪他系统数据灵活交互的原因。通常,其他系统提供一个硬盘或内存与数据的对应关系,使得利用C或Fortran等底层语言读写数据变得十分方便。

名称 描述
bool_ 布尔型数据类型(True 或者 False)
int_ 默认的整数类型(类似于 C 语言中的 long,int32 或 int64)
intc 与 C 的 int 类型一样,一般是 int32 或 int 64
intp 用于索引的整数类型(类似于 C 的 ssize_t,一般情况下仍然是 int32 或 int64)
int8 字节(-128 to 127)
int16 整数(-32768 to 32767)
int32 整数(-2147483648 to 2147483647)
int64 整数(-9223372036854775808 to 9223372036854775807)
uint8 无符号整数(0 to 255)
uint16 无符号整数(0 to 65535)
uint32 无符号整数(0 to 4294967295)
uint64 无符号整数(0 to 18446744073709551615)
float_ float64 类型的简写
float16 半精度浮点数,包括:1 个符号位,5 个指数位,10 个尾数位
float32 单精度浮点数,包括:1 个符号位,8 个指数位,23 个尾数位
float64 双精度浮点数,包括:1 个符号位,11 个指数位,52 个尾数位
complex_ complex128 类型的简写,即 128 位复数
complex64 复数,表示双 32 位浮点数(实数部分和虚数部分)
complex128 复数,表示双 64 位浮点数(实数部分和虚数部分)

使用astype方法来显式的转换数组的数据类型

arr = np.array([1,2,3,4,5])
print(arr.dtype)
print(arr)
float_arr = arr.astype('float32')#也可以写作 arr.astype(np.float32)
print(float_arr.dtype)
print(float_arr)

int32
[1 2 3 4 5]
float32
[1. 2. 3. 4. 5.]

注意:将内容为数字的字符串数组转为数字是可以的,当内容是浮点型数字的时候只能转成 float,不能 int,只有是整数的时候才可以转成int

用其他数组的dtype来转换数据类型:

int_arr = np.arange(10)
calibers = np.array([.22, .270, .357], dtype=np.float64)
print(calibers)
arr_last = int_arr.astype(calibers.dtype)
print(arr_last.dtype)
print(arr_last)

[0.22 0.27 0.357]
float64
[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]

猜你喜欢

转载自www.cnblogs.com/chanyuli/p/11716951.html