Numpy库基础___五
Numpy数据存取
•NumPy的随机数函数
View Codea = np.random.rand(1,2,3) print(a) #[[[0.03339719 0.72784732 0.47527802] # [0.6456671 0.65639799 0.01300073]]] a = np.random.randn(1,2,3) print(a) #[[[ 0.59115211 -0.40289048 1.34532466] # [-0.04616715 -0.64066822 -1.09722129]]] a = np.random.randint(100,200,(3,4)) print(a) #[[161 131 187 134] # [156 114 104 180] # [182 163 158 121]] #随机数种子,10是给定的种子值 np.random.seed(10) a = np.random.randint(100,200,(3,4)) print(a) #[[109 115 164 128] # [189 193 129 108] # [173 100 140 136]]View Codea = np.random.randint(100,200,(3,4)) print(a) #[[184 199 152 144] # [173 171 179 144] # [133 105 197 143]] np.random.shuffle(a) print(a) #[[173 171 179 144] # [133 105 197 143] # [184 199 152 144]] b = np.random.permutation(a) #[[173 171 179 144] # [133 105 197 143] # [184 199 152 144]] print(b) #[[133 105 197 143] # [173 171 179 144] # [184 199 152 144]] a = np.random.randint(100,200,(8,)) print(a) #[131 195 130 165 177 107 197 132] b = np.random.choice(a,(3,2)) print(b) #[[195 107] # [177 197] # [130 107]] b = np.random.choice(a,(3,2),replace=False) #[[107 130] # [197 132] # [195 131]] #加权,元素出现次数越多,被抽取的概率越高 b = np.random.choice(a,(3,2),p=a/np.sum(a)) print(b) #[[197 130] # [131 130] # [131 130]]View Codeu = np.random.uniform(0,10,(3,4)) print(u) #[[7.49328353 4.35990777 8.19266316 5.02229727] # [2.21122875 9.61785352 9.90294149 2.44401573] # [3.88367203 9.22037768 7.87306998 2.00241521]] u = np.random.normal(10,5,(3,4)) print(u) #[[13.44007699 10.5502136 14.79616224 -2.17381553] # [10.42238979 10.12351539 2.8561042 16.78322252] # [11.90679396 6.75343566 8.01259211 14.96874378]] u = np.random.poission(2,(3,4)) print(u) #[[4 0 1 2] # [2 2 3 2] # [0 0 2 3]]
•NumPy的统计函数
View Codea = np.arange(15).reshape(3,5) print(a) #[[ 0 1 2 3 4] # [ 5 6 7 8 9] # [10 11 12 13 14]] print(np.sum(a)) #105 print(np.sum(a,axis=0)) #[15 18 21 24 27] print(np.sum(a,axis=1)) #[10 35 60] print(np.mean(a)) #7.0 print(np.mean(a,axis=0)) #[5. 6. 7. 8. 9.] print(np.mean(a,axis=1)) #[ 2. 7. 12.] print(np.average(a)) #7.0 print(np.average(a,axis=0,weights=[1,2,3])) #[ 6.66666667 7.66666667 8.66666667 9.66666667 10.66666667]View Codea = np.arange(12).reshape(3,4) print(a) #[[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] print(np.min(a)) #0 print(np.max(a)) #11 print(np.argmin(a)) #0 print(np.argmax(a)) #11 print(np.unravel_index(10,(4,3))) #(3,1) print(np.unravel_index(np.argmax(a),(4,3))) #(3,2) print(np.ptp(a)) #11 print(np.median(a)) #5.5
•NumPy的梯度函数
- np.gradient(f):计算数组f中元素的梯度,当f为多维时,返回每个维度梯度
梯度:连续值之间的变化率,即斜率
X坐标轴连续三个x坐标对应的Y轴值:a,b,c其中b的梯度时(c-a)/2
a = np.random.randint(0,20,(5,)) print(a) #[ 2 10 11 14 12] print(np.gradient(a)) #[ 8. 4.5 2. 0.5 -2. ]