numpy具有不同的数据类型的结构化数组

numpy普通数组转结构化数组

普通数组类似矩阵,结构化数组类似结构体。他们的索引方式相同,但是结构化数组支持names索引。

查看数组的数据类型

a.dtype
#dtype((numpy.record, [('names0', '<U20'), ('names1', '|S8'), ('names2', '<f8'), ('names3', '<i8')]))

普通数组的数据格式类型是统一的,结构化数组的数据类型可以不同,dtype为类型名+位长,例如6个字符就是S6或者U6,单精度浮点数就是f4。

类型 类型代码 说明
int8 i1 整型
int16 i2 整型
uint16 u2 无符号整型
int32 i4 整型
unit32 u4 无符号整型
int64 i8 整形
float16 f2 半精度
float32 f4/f 单精度
float64 f8/d 双精度
bool ? 布尔型True/False
object O python对象
string_ S 字符串
unicode_ U unicode

数组的数据类型转变

import numpy as np
a  = 9.9 * np.ones(( 100,3 ))
a.astype(int)
a.astype(str)

列表和普通数组转结构化数组

import numpy as np
a        = 9.9 * np.ones((10,3))
a        = np.hstack(( np.arange(100),a ))
struct   = {'names':('num','col01','col02'), 'formats':('U3','int','float')}
a_struct = np.rec.array( a.tolist(), dtype=struct )
# index if return one element
a[5]['col01']
# index if return multi elements
a[5][['num','col01']]
posted @ 2022-03-24 16:17  Philbert  阅读(331)  评论(0编辑  收藏  举报