NumPy快速入门--基础知识
文章目錄
- 1. 一個典型例子
- 2. 數組的創建
- 3. 打印數組
- 4. 基本操作
- 5. 通用函數
- 6. 索引、切片、迭代
NumPy的數組類被稱為ndarray。別名為 array。
- ndarray.ndim:數組的軸(維度)的個數。又稱為rank。
- ndarray.shape:數組的維度。是一個整數的元組,對于有n行和m列的矩陣,shape將是(n,m)。因此,shape元組的長度就是rank或維度的個數 ndim。
- ndarray.size:數組元素的總數。等于shape的元素的乘積。
- ndarray.dtype:數組中元素類型的對象。可以使用標準的Python類型創建或指定dtype。另外NumPy提供它自己的類型。例如numpy.int32、numpy.int16和numpy.float64。
- ndarray.itemsize:數組中每個元素的字節大小。例如,元素為 float64 類型的數組的 itemsize 為8(=64/8),而 complex32 類型的數組的 itemsize 為4(=32/8)。它等于 ndarray.dtype.itemsize 。
- ndarray.data:該緩沖區包含數組的實際元素。通常,我們不需要使用此屬性,因為我們將使用索引訪問數組中的元素。
1. 一個典型例子
>>> import numpy as np >>> a = np.arange(15).reshape(3,5) >>> a array([[ 0, 1, 2, 3, 4],[ 5, 6, 7, 8, 9],[10, 11, 12, 13, 14]])>>> a.shape (3, 5)>>> a.ndim 2>>> a.dtype.name 'int32'>>> a.itemsize 4>>> a.size 15>>> type(a) <class 'numpy.ndarray'>>>> b = np.array([6,7,8]) >>> b array([6, 7, 8])>>> type(b) <class 'numpy.ndarray'>2. 數組的創建
np.array() 傳入的是一個列表 [ ]
>>> a = np.array(1,2,3,4) # WRONG可以指定數組類型
>>> c = np.array([[1,2],[3,4]],dtype=complex) >>> c array([[1.+0.j, 2.+0.j],[3.+0.j, 4.+0.j]]) >>> c.dtype dtype('complex128')np.arange
>>> np.arange(10,30,5) #(start, end, step) 不包括end array([10, 15, 20, 25]) >>> np.arange(0,2,0.3) # 浮點精度優先,有時元素數量不能準確提前知道 array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])np.linspace
>>> from numpy import pi >>> np.linspace(0, 2, 9) ## 9 numbers from 0 to 2 array([0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ]) >>> x = np.linspace(0, 2*pi, 100) >>> x array([0. , 0.06346652, 0.12693304, 0.19039955, 0.25386607,0.31733259, 0.38079911, 0.44426563, 0.50773215, 0.57119866,0.63466518, 0.6981317 , 0.76159822, 0.82506474, 0.88853126,0.95199777, 1.01546429, 1.07893081, 1.14239733, 1.20586385,1.26933037, 1.33279688, 1.3962634 , 1.45972992, 1.52319644,1.58666296, 1.65012947, 1.71359599, 1.77706251, 1.84052903,1.90399555, 1.96746207, 2.03092858, 2.0943951 , 2.15786162,2.22132814, 2.28479466, 2.34826118, 2.41172769, 2.47519421,2.53866073, 2.60212725, 2.66559377, 2.72906028, 2.7925268 ,2.85599332, 2.91945984, 2.98292636, 3.04639288, 3.10985939,3.17332591, 3.23679243, 3.30025895, 3.36372547, 3.42719199,3.4906585 , 3.55412502, 3.61759154, 3.68105806, 3.74452458,3.8079911 , 3.87145761, 3.93492413, 3.99839065, 4.06185717,4.12532369, 4.1887902 , 4.25225672, 4.31572324, 4.37918976,4.44265628, 4.5061228 , 4.56958931, 4.63305583, 4.69652235,4.75998887, 4.82345539, 4.88692191, 4.95038842, 5.01385494,5.07732146, 5.14078798, 5.2042545 , 5.26772102, 5.33118753,5.39465405, 5.45812057, 5.52158709, 5.58505361, 5.64852012,5.71198664, 5.77545316, 5.83891968, 5.9023862 , 5.96585272,6.02931923, 6.09278575, 6.15625227, 6.21971879, 6.28318531]) >>> f = np.sin(x) >>> f array([ 0.00000000e+00, 6.34239197e-02, 1.26592454e-01, 1.89251244e-01,2.51147987e-01, 3.12033446e-01, 3.71662456e-01, 4.29794912e-01,4.86196736e-01, 5.40640817e-01, 5.92907929e-01, 6.42787610e-01,6.90079011e-01, 7.34591709e-01, 7.76146464e-01, 8.14575952e-01,8.49725430e-01, 8.81453363e-01, 9.09631995e-01, 9.34147860e-01,9.54902241e-01, 9.71811568e-01, 9.84807753e-01, 9.93838464e-01,9.98867339e-01, 9.99874128e-01, 9.96854776e-01, 9.89821442e-01,9.78802446e-01, 9.63842159e-01, 9.45000819e-01, 9.22354294e-01,8.95993774e-01, 8.66025404e-01, 8.32569855e-01, 7.95761841e-01,7.55749574e-01, 7.12694171e-01, 6.66769001e-01, 6.18158986e-01,5.67059864e-01, 5.13677392e-01, 4.58226522e-01, 4.00930535e-01,3.42020143e-01, 2.81732557e-01, 2.20310533e-01, 1.58001396e-01,9.50560433e-02, 3.17279335e-02, -3.17279335e-02, -9.50560433e-02,-1.58001396e-01, -2.20310533e-01, -2.81732557e-01, -3.42020143e-01,-4.00930535e-01, -4.58226522e-01, -5.13677392e-01, -5.67059864e-01,-6.18158986e-01, -6.66769001e-01, -7.12694171e-01, -7.55749574e-01,-7.95761841e-01, -8.32569855e-01, -8.66025404e-01, -8.95993774e-01,-9.22354294e-01, -9.45000819e-01, -9.63842159e-01, -9.78802446e-01,-9.89821442e-01, -9.96854776e-01, -9.99874128e-01, -9.98867339e-01,-9.93838464e-01, -9.84807753e-01, -9.71811568e-01, -9.54902241e-01,-9.34147860e-01, -9.09631995e-01, -8.81453363e-01, -8.49725430e-01,-8.14575952e-01, -7.76146464e-01, -7.34591709e-01, -6.90079011e-01,-6.42787610e-01, -5.92907929e-01, -5.40640817e-01, -4.86196736e-01,-4.29794912e-01, -3.71662456e-01, -3.12033446e-01, -2.51147987e-01,-1.89251244e-01, -1.26592454e-01, -6.34239197e-02, -2.44929360e-16])3. 打印數組
NumPy以與嵌套列表類似的方式,具有以下布局:
- 最后一個軸從左到右打印,
- 倒數第二個從上到下打印,
- 其余的也從上到下打印,每個切片與下一個用空行分開。
一維數組被打印為行、二維為矩陣和三維為矩陣列表。
>>> a = np.arange(6) # 1D 數組 >>> print(a) [0 1 2 3 4 5]>>> b = np.arange(12).reshape(4,3) # 2D 數組 >>> print(b) [[ 0 1 2][ 3 4 5][ 6 7 8][ 9 10 11]]>>> c = np.arange(24).reshape(2,3,4) # 3D 數組 >>> print(c) [[[ 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(np.arange(10000)) [ 0 1 2 ... 9997 9998 9999]>>> print(np.arange(10000).reshape(100,100)) [[ 0 1 2 ... 97 98 99][ 100 101 102 ... 197 198 199][ 200 201 202 ... 297 298 299]...[9700 9701 9702 ... 9797 9798 9799][9800 9801 9802 ... 9897 9898 9899][9900 9901 9902 ... 9997 9998 9999]] np.set_printoptions(threshold=10000) #元素總數 > 閾值,顯示部分,否則顯示全部 >>> np.set_printoptions(threshold=140) >>> print(np.arange(144).reshape(12,12))[[ 0 1 2 ... 9 10 11][ 12 13 14 ... 21 22 23][ 24 25 26 ... 33 34 35]...[108 109 110 ... 117 118 119][120 121 122 ... 129 130 131][132 133 134 ... 141 142 143]]>>> np.set_printoptions(threshold=145) >>> print(np.arange(144).reshape(12,12))[[ 0 1 2 3 4 5 6 7 8 9 10 11][ 12 13 14 15 16 17 18 19 20 21 22 23][ 24 25 26 27 28 29 30 31 32 33 34 35][ 36 37 38 39 40 41 42 43 44 45 46 47][ 48 49 50 51 52 53 54 55 56 57 58 59][ 60 61 62 63 64 65 66 67 68 69 70 71][ 72 73 74 75 76 77 78 79 80 81 82 83][ 84 85 86 87 88 89 90 91 92 93 94 95][ 96 97 98 99 100 101 102 103 104 105 106 107][108 109 110 111 112 113 114 115 116 117 118 119][120 121 122 123 124 125 126 127 128 129 130 131][132 133 134 135 136 137 138 139 140 141 142 143]]4. 基本操作
一個新的數組被創建并填充結果
>>> a = np.array([20,30,40,50]) >>> b = np.arange(4) >>> b array([0, 1, 2, 3]) >>> c = a - b >>> c array([20, 29, 38, 47]) >>> b**2 #平方 array([0, 1, 4, 9], dtype=int32) >>> 10*np.sin(a) #單位弧度 array([ 9.12945251, -9.88031624, 7.4511316 , -2.62374854]) >>> a<35 array([ True, True, False, False])與許多矩陣語言不同,乘法運算符 * 的運算在NumPy數組中是元素級別的。矩陣乘積可以使用 dot 函數或方法執行:
>>> A = np.array( [[1,1], ... [0,1]] ) >>> B = np.array( [[2,0], ... [3,4]] ) >>> A*B #對應元素相乘 array([[2, 0],[0, 4]])>>> A.dot(B) #矩陣乘積 dot(matrix) array([[5, 4],[3, 4]]) >>> np.dot(A,B) array([[5, 4],[3, 4]]) >>> B.dot(A) array([[2, 2],[3, 7]])某些操作(例如+=和*=)適用于修改現有數組,不創建新數組。
>>> a = np.ones((2,3),dtype=int) >>> b = np.random.random((2,3)) >>> a array([[1, 1, 1],[1, 1, 1]]) >>> b array([[0.43420493, 0.10561194, 0.44199609],[0.07220352, 0.26078137, 0.24609001]]) >>> a *= 3 >>> a array([[3, 3, 3],[3, 3, 3]]) >>> b += a >>> b array([[3.43420493, 3.10561194, 3.44199609],[3.07220352, 3.26078137, 3.24609001]]) >>> a += b # b 不能自動轉化成int型 Traceback (most recent call last):File "<pyshell#36>", line 1, in <module>a += b numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int32') with casting rule 'same_kind'當不同類型的數組操作時,結果數組的類型對應于更精確的數組(向上轉換的行為)。
>>> a = np.ones(3, dtype=np.int32) >>> b = np.linspace(0,pi,3) >>> b.dtype.name 'float64' >>> c = a+b >>> c array([ 1. , 2.57079633, 4.14159265]) >>> c.dtype.name 'float64' >>> d = np.exp(c*1j) >>> d array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,-0.54030231-0.84147098j]) >>> d.dtype.name 'complex128'許多一元運算,例如計算數組中所有元素的總和,都是作為 ndarray 類的方法實現的。
>>> a = np.random.random((2,3)) # 2行3列 0-1之間的隨機數 >>> a array([[0.29421273, 0.96663251, 0.67232279],[0.83508847, 0.58010047, 0.76200929]]) >>> a.sum() 4.110366271979025 >>> a.min() 0.29421272607104476 >>> a.max() 0.9666325116204056默認情況下,這些操作適用于數組,就好像它是數字列表一樣,無論其形狀如何。但是,通過指定 axis 參數,你可以沿著數組的指定軸應用操作:
>>> b = np.arange(12).reshape(3,4) >>> b array([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11]]) >>> >>> b.sum(axis=0) #axis=0,表示按列操作 array([12, 15, 18, 21]) >>> b.min(axis=1) # axis=1,表示按行操作 array([0, 4, 8])>>> b.cumsum(axis=1) #按行累積和 array([[ 0, 1, 3, 6],[ 4, 9, 15, 22],[ 8, 17, 27, 38]], dtype=int32) >>> b.cumsum(axis=0) #按列累積和 array([[ 0, 1, 2, 3],[ 4, 6, 8, 10],[12, 15, 18, 21]], dtype=int32)5. 通用函數
NumPy提供了常見的數學函數,如sin,cos和exp。In NumPy, these are called “universal functions”( ufunc ). 在NumPy中,這些函數在數組上按元素級別操作,產生一個數組作為輸出。
>>> B = np.arange(3) >>> B array([0, 1, 2]) >>> np.exp(B) array([1. , 2.71828183, 7.3890561 ]) >>> np.sqrt(B) array([0. , 1. , 1.41421356]) >>> C = np.array([2, -1, 4]) >>> np.add(B, C) array([2, 0, 6])6. 索引、切片、迭代
一維數組可以被索引,切片和迭代,就像列出和其他Python序列一樣。
>>> a = np.arange(10)**3 >>> a array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729], dtype=int32) >>> a[2] 8 >>> a[2:5] #不包含最后一個 array([ 8, 27, 64], dtype=int32) >>> a[:6:2] = -1000 #從最開始到6(不含6),每2個元素置 -1000 >>> a array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512,729], dtype=int32) >>> a[::-1] # 反向序列 a‘ array([ 729, 512, 343, 216, 125, -1000, 27, -1000, 1,-1000], dtype=int32) >>> for i in a:print(i**(1/3))Warning (from warnings module):File "__main__", line 2 RuntimeWarning: invalid value encountered in power nan 1.0 nan 3.0 nan 5.0 5.999999999999999 6.999999999999999 7.999999999999999 8.999999999999998 >>> a = np.random.rand(5) >>> a array([0.44659638, 0.10928946, 0.54948707, 0.08119349, 0.92727562]) >>> a[-1] # 最后一個元素 0.9272756224719964 >>> a[:-1] # 除了最后一個的其余的 array([0.44659638, 0.10928946, 0.54948707, 0.08119349]) >>> a[::-1] # 逆序輸出新的序列 array([0.92727562, 0.08119349, 0.54948707, 0.10928946, 0.44659638]) >>> a[2::-1] # 從下標2的元素向前全部讀取 array([0.54948707, 0.10928946, 0.44659638])多維(Multidimensional) 數組每個軸可以有一個索引。 這些索在元組中以逗號分隔給出:
>>> def f(x,y):return 10*x+y>>> b = np.fromfunction(f,(5,4),dtype=int) >>> b array([[ 0, 1, 2, 3],[10, 11, 12, 13],[20, 21, 22, 23],[30, 31, 32, 33],[40, 41, 42, 43]]) >>> b[2,3] 23 >>> b[0:5,1] # 0,1,2,3,4行,每行取下標1的列元素 array([ 1, 11, 21, 31, 41])>>> b[ : ,1] # 所有行,取下標1的列元素 array([ 1, 11, 21, 31, 41])>>> b[1:3,:] # 1,2行,所有的列元素 array([[10, 11, 12, 13],[20, 21, 22, 23]])當提供比軸數更少的索引時,缺失的索引被認為是一個完整切片 :
>>> b[-1] # 最后一行,即 b[-1, :] array([40, 41, 42, 43])b[i] 方括號中的表達式 i 被視為后面緊跟著 : 的多個實例,用于表示剩余軸。NumPy也允許你使用三個點寫為 b[i,...]。
三個點( ... )表示產生完整索引元組所需的冒號。例如,如果 x 是rank為的5數組(即,它具有5個軸),則
x[1,2,...] 等于 x[1,2,:,:,:]
x[...,3] 等效于 x[:,:,:,:,3]
x[4,...,5,:] 等效于 x[4,:,:,5,:]
迭代(Iterating) 多維數組是相對于第一個軸完成的:
>>> for row in b:print(row)[0 1 2 3] [10 11 12 13] [20 21 22 23] [30 31 32 33] [40 41 42 43]但是,如果想要對數組中的每個元素執行操作,可以使用 flat 屬性,該屬性是數組中所有元素的迭代器:
>>> for element in b.flat:print(element)0 1 2 3 10 11 12 13 20 21 22 23 30 31 32 33 40 41 42 43總結
以上是生活随笔為你收集整理的NumPy快速入门--基础知识的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 287. 寻找重复数(
- 下一篇: python比较时间的最大值_时间戳的最