1、幾種常見numpy的屬性
- ndim:維度
- shape:行數和列數
- size:元素個數
1 >>> import numpy as np #導入numpy模塊,np是為了使用方便的簡寫 2 >>> array = np.array([[1,2,3],[2,3,4]]) #列表轉化為矩陣 3 >>> print(array) 4 [[1 2 3] 5 [2 3 4]] 6 >>> 7 >>> print('number of dim:',array.ndim) # 維度 8 number of dim: 2 9 >>> print('shape :',array.shape) # 行數和列數 10 shape : (2, 3) 11 >>> print('size:',array.size) # 元素個數 12 size: 6
2、Numpy創建array
2.1 關鍵字
- array:創建數組
- dtype:制定數據類型
- zeros:創建數據全為0
- ones:創建數據全為1
- empty:創建數據接近0
- arrange:按指定范圍創建數據
- linspace:創建線段
2.2 創建數組
1 #創建數組 2 >>> a = np.array([2,23,4]) # list 1d 3 >>> print(a) 4 [ 2 23 4] 5 6 #指定類型 7 >>> a = np.array([2,23,4],dtype=np.int) 8 >>> print(a.dtype) 9 int32 10 11 >>> a = np.array([2,23,4],dtype=np.int32) 12 >>> print(a.dtype) 13 int32 14 15 >>> a = np.array([2,23,4],dtype=np.float) 16 >>> print(a.dtype) 17 float64 18 19 >>> a = np.array([2,23,4],dtype=np.float32) 20 >>> print(a.dtype) 21 float32 22 23 #創建特定數據 24 >>> a = np.array([[2,23,4],[2,32,4]]) # 2d 矩陣 2行3列 25 >>> print(a) 26 [[ 2 23 4] 27 [ 2 32 4]] 28 29 #創建全零數組 30 >>> a = np.zeros((3,4)) # 數據全為0,3行4列 31 >>> print(a) 32 [[0. 0. 0. 0.] 33 [0. 0. 0. 0.] 34 [0. 0. 0. 0.]] 35 36 #創建全1數組 37 >>> a = np.ones((3,4),dtype = np.int) # 數據為1,3行4列 38 >>> print(a) 39 [[1 1 1 1] 40 [1 1 1 1] 41 [1 1 1 1]] 42 43 #創建全空數組, 其實每個值都是接近於零的數: 44 >>> a = np.empty((3,4)) # 數據為empty,3行4列 45 >>> print(a) 46 [[0. 0. 0. 0.] 47 [0. 0. 0. 0.] 48 [0. 0. 0. 0.]] 49 50 #用 arange 創建連續數組: 51 >>> a = np.arange(10,20,2) # 10-19 的數據,2步長 52 >>> print(a) 53 [10 12 14 16 18] 54 55 #使用 reshape 改變數據的形狀 56 >>> a = np.arange(12).reshape((3,4)) # 3行4列,0到11 57 >>> print(a) 58 [[ 0 1 2 3] 59 [ 4 5 6 7] 60 [ 8 9 10 11]] 61 62 #用 linspace 創建線段型數據: 63 >>> a = np.linspace(1,10,20) # 開始端1,結束端10,且分割成20個數據,生成線段 64 >>> print(a) 65 [ 1. 1.47368421 1.94736842 2.42105263 2.89473684 3.36842105 66 3.84210526 4.31578947 4.78947368 5.26315789 5.73684211 6.21052632 67 6.68421053 7.15789474 7.63157895 8.10526316 8.57894737 9.05263158 68 9.52631579 10. ] 69 70 71 #同樣也能進行 reshape 工作: 72 >>> a = np.linspace(1,10,20).reshape((5,4)) # 更改shape 73 >>> print(a) 74 [[ 1. 1.47368421 1.94736842 2.42105263] 75 [ 2.89473684 3.36842105 3.84210526 4.31578947] 76 [ 4.78947368 5.26315789 5.73684211 6.21052632] 77 [ 6.68421053 7.15789474 7.63157895 8.10526316] 78 [ 8.57894737 9.05263158 9.52631579 10. ]]