9. 结构化数据

  • 用于存储异构数值,类似c语言的结构
  • 复杂结构建议使用Pandas的DataFrame

9.1. 结构化数组初体验

# 定义一个学生信息数组,包括姓名,成绩,身高
x = np.zeros(4, dtype={"names":("name", "score", "heigh"), \
                      "formats":("U10", "i4", "f8")})

print("x = ", x)
print("x.dtype = ", x.dtype)
x =  [('', 0, 0.) ('', 0, 0.) ('', 0, 0.) ('', 0, 0.)]
x.dtype =  [('name', '<U10'), ('score', '<i4'), ('heigh', '<f8')]
# 可以对某一项进行统一赋值
x['name'] = "LIU Ying"
x['score'] = 98
x['heigh'] = 185

print("统一赋值后的x = \n", x )
统一赋值后的x = 
 [('LIU Ying', 98, 185.) ('LIU Ying', 98, 185.) ('LIU Ying', 98, 185.)
 ('LIU Ying', 98, 185.)]
# 可以采用key的形式进行访问列
print("学生的姓名是: ", x['name'])

# 也可以采用索引的形式进行访问行
print("第一行的同学是: ", x[0])
学生的姓名是:  ['LIU Ying' 'LIU Ying' 'LIU Ying' 'LIU Ying']
第一行的同学是:  ('LIU Ying', 98, 185.)
# 可以对结构化数据进行批量赋值

names = ["Alice", "Bob", "Cindy", "Day"]
score = [86, 45,68,98]
heigh = [154, 184, 198,178]

x["name"] = names
x["score"] = score
x["heigh"] = heigh

print("统一赋值后的 x = \n", x)
统一赋值后的 x = 
 [('Alice', 86, 154.) ('Bob', 45, 184.) ('Cindy', 68, 198.)
 ('Day', 98, 178.)]
# 结构化数据的掩码操作
# 选择成绩小于90的同学的姓名
print(x[x['score'] < 90]['name'])
['Alice' 'Bob' 'Cindy']

9.2. 结构化数据的常用类型定义方式

结构化数组的类型的定义方式比较灵活,常用的有以下几种方式:

# 1. 使用字典作为机构化数组的类型

a = np.dtype({"names":("name", "score", "heigh"), \
                      "formats":("U10", "i4", "f8")})
print(a)
[('name', '<U10'), ('score', '<i4'), ('heigh', '<f8')]
# 2. 使用python数据类型或者NumPy的dtype类型

b = np.dtype({"names":("name", "score", "heigh"), \
                      "formats":((np.str_, 10), int, float)})

print(b)
[('name', '<U10'), ('score', '<i4'), ('heigh', '<f8')]
# 3. 如果类型的名称不重要, 可以省略
c = np.dtype("S10, i4, f8")
print(c)
[('f0', 'S10'), ('f1', '<i4'), ('f2', '<f8')]
# 4. 复合类型
# 此类型类似C语言中的结构
import numpy as np

# 定义一个结构
tp = np.dtype([('id', 'i8'), ('mat', 'f8', (4,4))])

# 利用定义的结构tp创建一份内容
x = np.zeros(2, dtype=tp)

#打印整个内容
print(x)

# 只打印出数据内容
print(x['mat'][0])
[(0, [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
 (0, [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])]
[[0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]
 [0. 0. 0. 0.]]