Numpy-03 结构数组
2020-03-26 本文已影响0人
罗泽坤
# 自定义结构数组
import numpy as np
persontype = np.dtype({'names':['name', 'age', 'chinese', 'math', 'english']#自定义命名空间,
,'formats':['U32','i', 'i', 'i', 'f']})
peoples = np.array([("ZhangFei",32,75,100, 90),("GuanYu",24,85,96,88.5),
("ZhaoYun",28,85,92,96.5),("HuangZhong",29,65,85,100)], dtype=persontype)
ages = peoples['age']
chineses = peoples['chinese']
maths = peoples['math']
englishs = peoples['english']
print(np.mean(ages))
print(np.mean(chineses))
print(np.mean(maths))
print(np.mean(englishs))
print(peoples['name'])
print(ages)
print(chineses)
print(maths)
print(englishs)
print(peoples)
print(peoples[0][1:])#不支持 此种切片索引因为数组是peoples是一维的
28.25
77.5
93.25
93.75
['ZhangFei' 'GuanYu' 'ZhaoYun' 'HuangZhong']
[32 24 28 29]
[75 85 85 65]
[100 96 92 85]
[ 90. 88.5 96.5 100. ]
[('ZhangFei', 32, 75, 100, 90. ) ('GuanYu', 24, 85, 96, 88.5)
('ZhaoYun', 28, 85, 92, 96.5) ('HuangZhong', 29, 65, 85, 100. )]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-98-30558e3ef830> in <module>
19 print(englishs)
20 print(peoples)
---> 21 print(peoples[0][1:])#不支持 此种切片索引因为数组是peoples是一维的
IndexError: too many indices for array
Meanlist = []
for i in range(peoples.size):
a = np.mean(list(peoples[i])[1:])
Meanlist.append((peoples[i][0],a))
print(Meanlist)
print(sorted(Meanlist,key=lambda x:x[1]))
[(b'ZhangFei', 74.25), (b'GuanYu', 73.375), (b'ZhaoYun', 75.375), (b'HuangZhong', 69.75)]
[(b'HuangZhong', 69.75), (b'GuanYu', 73.375), (b'ZhangFei', 74.25), (b'ZhaoYun', 75.375)]
#自定义数据类型
#下面的代码格式不对
dt = np.dtype([[s32,i,i,i,f]])
hero = np.array([["ZhangFei",32,75,100, 90],["GuanYu",24,85,96,88.5],
["ZhaoYun",28,85,92,96.5],["HuangZhong",29,65,85,100]],dtype=dt)
print(hero)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-55-7dd6262c0288> in <module>
1 #自定义数据类型
----> 2 dt = np.dtype([[s32,i,i,i,f]])
3 hero = np.array([["ZhangFei",32,75,100, 90],["GuanYu",24,85,96,88.5],
4 ["ZhaoYun",28,85,92,96.5],["HuangZhong",29,65,85,100]],dtype=dt)
5 print(hero)
NameError: name 's32' is not defined
print(Meanlist)
Meanlist.sort(key = lambda x:x[1],reverse=True)
print(Meanlist)
[(b'HuangZhong', 69.75), (b'GuanYu', 73.375), (b'ZhangFei', 74.25), (b'ZhaoYun', 75.375)]
[(b'ZhaoYun', 75.375), (b'ZhangFei', 74.25), (b'GuanYu', 73.375), (b'HuangZhong', 69.75)]
print(peoples)
[(b'ZhangFei', 32, 75, 100, 90. ) (b'GuanYu', 24, 85, 96, 88.5)
(b'ZhaoYun', 28, 85, 92, 96.5) (b'HuangZhong', 29, 65, 85, 100. )]
print(peoples['math'].argmax())
print('数学最高分是',peoples[peoples['math'].argmax()][0],peoples['math'].max(),'分')
0
数学最高分是 ZhangFei 100 分
github代码地址
https://github.com/luozekun1230/MyPyhonProgram/tree/master/Python%E5%9F%BA%E7%A1%80