Numpy:自定义复合数据类型

Numpy的自定义复合数据类型

'''
numpy自定义复合类型
在ndarray数组中存储3位学生信息(三个字段:姓名、成绩、年龄)
'''
import numpy as np

data = [('zs', [10, 15, 2], 3),
        ('ls', [12, 12, 92], 8),
        ('ww', [14, 35, 82], 13)]

# 第一种设置dtype的方式
a = np.array(data,
             dtype='U2, 3i4, i4')
print(a, '; zs.age:', a[0]['f2'])

# 第二种设置dtype的方式
b = np.array(data, dtype=[
    ('name', 'str_', 2),
    ('scores', 'int32', 3),
    ('age', 'int32', 1)])
print(b, '; ww.age:', b[2]['age'])

# 第三种设置dtype的方式
c = np.array(data, dtype={
    'names': ['name', 'scores', 'age'],
    'formats': ['U2', '3int32', 'int32']})
print(c, '; ls.name:', c[1]['name'])
原文地址:https://www.cnblogs.com/wodexk/p/10308106.html