python数据分析2之numpy
源代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 # -*- coding: utf-8 -*- 2 """ 3 Spyder Editor 4 5 This is a temporary script file. 6 """ 7 8 import numpy as np 9 a = np.array([1, 2, 3]) 10 b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) 11 b[1,1]=10 12 print(a.shape)#3 13 print(b.shape)#(3,3) 14 print(a.dtype)#int32 15 16 import numpy as np 17 persontype = np.dtype({ 18 'names':['name', 'age', 'chinese', 'math', 'english'], 19 'formats':['S32','i', 'i', 'i', 'f']}) 20 peoples = np.array([("lisi",32,75,100, 90),("wangW",24,85,96,88.5), 21 ("ZhaoYun",28,85,92,96.5),("HuangZhong",29,65,85,100)], 22 dtype=persontype) 23 ages = peoples[:]['age'] 24 chineses = peoples[:]['chinese'] 25 maths = peoples[:]['math'] 26 englishs = peoples[:]['english'] 27 print(np.mean(ages))#计算平均值 28 print(np.mean(chineses)) 29 print(np.mean(maths)) 30 print(np.mean(englishs)) 31 32 x1 = np.arange(1,11,2) 33 x2 = np.linspace(1,9,5) 34 35 x1 = np.arange(1,11,2) 36 x2 = np.linspace(1,9,5) 37 print(np.add(x1, x2))#[ 2. 6. 10. 14. 18.] 38 print(np.subtract(x1, x2)) 39 #print(np.multiply((x1,x2))) 40 print(np.divide(x1, x2)) 41 print(np.power(x1, x2)) 42 print(np.remainder(x1, x2)) 43 44 45 import numpy as np 46 a=np.array([[1,2,3],[4,5,6],[7,8,9]]) 47 print(np.amin(a))#1 48 print(np.amin(a,0))#[1 2 3] 49 50 print(np.amin(a,1)) #[1 4 7] 51 print(np.amax(a))#9 52 print(np.amax(a,0))#[7 8 9] 53 print(np.amax(a,1))#[3 6 9] 54 55 a = np.array([[1,2,3], [4,5,6], [7,8,9]]) 56 print(np.ptp(a))#8 所有元素中最大和最小的差值 57 print(np.ptp(a,0))#[6 6 6] 58 print(np.ptp(a,1))#[2 2 2] 59 60 a = np.array([1,2,3,4]) 61 wts = np.array([1,2,3,4]) 62 print(np.average(a))#2.5 63 #print(np.average((a,weights=wts)) 64 65 a = np.array([1,2,3,4]) 66 print(np.std(a)) 67 print(np.var(a)) 68 69 a = np.array([[4,3,2],[2,4,1]]) 70 print(np.sort(a))#每个子元素排序 71 print(np.sort(a, axis=None))# 72 print(np.sort(a, axis=0)) 73 print(np.sort(a, axis=1))