python学习numpy之数组
一、
import numpy as np t4 = np.array(range(1,4),dtype = "int8") print(t4) #bool类型 t5 = np.array([1,0,1,0,1],dtype="bool") print(t5) print(t5.dtype) #调整数据类型 t6 = t5.astype("int8") print(t6) [1 0 1 0 1] #创建数组 t1 = np.arange(10) print(t1) #random方法 import random t7 = np.array([random.random() for i in range(10)]) print(t7) #调整小数位数 t8 = np.round(t7,2) print(t8) #取小数例子 print(round(random.random(),2)) print("%0.2f"%random.random()) [0.87507379 0.4408964 0.31392349 0.44701067 0.74086082 0.62657575 0.27928578 0.89692359 0.32012547 0.79427387] [0.88 0.44 0.31 0.45 0.74 0.63 0.28 0.9 0.32 0.79] 0.54 0.02 #shape,第一个行数,第二个列数;若数组是一维的,则第一个数表示元素个数 #shape,数值个数,表示维数 a1 = np.arange(12) print(a1.shape) a2 = np.array([[1,2,3],[4,5,6]]) print(a2) print(a2.shape) (12,) [[1 2 3] [4 5 6]] (2, 3)
#修改数组维数,reshape. 对数据本身修改不了 a3 = np.arange(10) a4 = a3.reshape(5,2) # 修改为5行2列 print(a4) a5 = np.arange(24).reshape(2,3,4) #三维数组 print(a5) a6 = a5.reshape((4,6)) print(a6) print(a5.reshape((24,))) [[0 1] [2 3] [4 5] [6 7] [8 9]] [[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[12 13 14 15] [16 17 18 19] [20 21 22 23]]] [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23]] [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23] #查看数据个数 a7 = a6.reshape((a6.shape[0]*a6.shape[1],)) #a6 行数乘以列数 print(a7) #查看数据个数,快捷方法 faltten a6.flatten() [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23] Out[26]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]) #数组与数字,数组与数字做计算,数字与数组里面每个数字做计算 print(a6+2) print(a6/2) print(a6-10) print(a6*2) print(a6/0) #nan不是数字,inf无限 [[ 2 3 4 5 6 7] [ 8 9 10 11 12 13] [14 15 16 17 18 19] [20 21 22 23 24 25]] [[ 0. 0.5 1. 1.5 2. 2.5] [ 3. 3.5 4. 4.5 5. 5.5] [ 6. 6.5 7. 7.5 8. 8.5] [ 9. 9.5 10. 10.5 11. 11.5]] [[-10 -9 -8 -7 -6 -5] [ -4 -3 -2 -1 0 1] [ 2 3 4 5 6 7] [ 8 9 10 11 12 13]] [[ 0 2 4 6 8 10] [12 14 16 18 20 22] [24 26 28 30 32 34] [36 38 40 42 44 46]] [[nan inf inf inf inf inf] [inf inf inf inf inf inf] [inf inf inf inf inf inf] [inf inf inf inf inf inf]] #数组与数组,两数组形状一致对应位置做计算,广播原则 a8 = np.arange(20,44).reshape((4,6)) print(a8) print(a8+a6) #数组与数组形状不一致的时候,有维度相同的地方,则维度相同的位置做计算。 a9 = np.arange(0,6) print(a6 - a9) a10 = np.arange(0,4).reshape(4,1) print(a10) print(a6-a10) #数组计算,若维度完全不同时,系统报错,计算不了 z1 = np.arange(10) print(a6-z1) [[20 21 22 23 24 25] [26 27 28 29 30 31] [32 33 34 35 36 37] [38 39 40 41 42 43]] [[20 22 24 26 28 30] [32 34 36 38 40 42] [44 46 48 50 52 54] [56 58 60 62 64 66]] [[ 0 0 0 0 0 0] [ 6 6 6 6 6 6] [12 12 12 12 12 12] [18 18 18 18 18 18]] [[0] [1] [2] [3]] [[ 0 1 2 3 4 5] [ 5 6 7 8 9 10] [10 11 12 13 14 15] [15 16 17 18 19 20]]

浙公网安备 33010602011771号