NumPy(Numeric Python)提供了許多高級的數值編程工具,如:矩陣數據類型、矢量處理,以及精密的運算庫。專為進行嚴格的數字處理而產生。多為很多大型金融公司使用,以及核心的科學計算組織如:Lawrence Livermore,NASA用其處理一些本來使用C++,Fortran或Matlab等所做的任務。
安裝Numpy可以通過 Pip 或者 Anaconda安裝Numpy:
或
本文目錄
基礎NumPy最常用的功能之一就是NumPy數組:列表和NumPy數組的最主要區別在於功能性和速度。
列表提供基本操作,但NumPy添加了FTTs、卷積、快速搜索、基本統計、線性代數、直方圖等。
兩者數據科學最重要的區別是能夠用NumPy數組進行元素級計算。
axis 0 通常指行
axis 1 通常指列
操作描述文檔np.array([1,2,3])一維數組https://numpy.org/doc/stable/reference/generated/numpy.array.html#numpy.arraynp.array([(1,2,3),(4,5,6)])二維數組https://numpy.org/doc/stable/reference/generated/numpy.array.html#numpy.arraynp.arange(start,stop,step)等差數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html佔位符操作描述文檔np.linspace(0,2,9)數組中添加等差的值https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.htmlnp.zeros((1,2))創建全0數組docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.htmlnp.ones((1,2))創建全1數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.ones.html#numpy.onesnp.random.random((5,5))創建隨機數的數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random.htmlnp.empty((2,2))創建空數組https://numpy.org/doc/stable/reference/generated/numpy.empty.html舉例:import numpy as np
# 1 dimensionalx = np.array([1,2,3])# 2 dimensionaly = np.array([(1,2,3),(4,5,6)])
x = np.arange(3)>>> array([0, 1, 2])
y = np.arange(3.0)>>> array([ 0., 1., 2.])
x = np.arange(3,7)>>> array([3, 4, 5, 6])
y = np.arange(3,7,2)>>> array([3, 5])
數組屬性數組屬性語法描述文檔array.shape維度(行,列)https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.htmllen(array)數組長度https://docs.python.org/3.5/library/functions.html#lenarray.ndim數組的維度數https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.ndim.htmlarray.size數組的元素數https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.size.htmlarray.dtype數據類型https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.htmlarray.astype(type)轉換數組類型https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.htmltype(array)顯示數組類型https://numpy.org/doc/stable/user/basics.types.html拷貝 /排序操作描述文檔np.copy(array)創建數組拷貝https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.htmlother = array.copy()創建數組深拷貝https://docs.scipy.org/doc/numpy/reference/generated/numpy.copy.htmlarray.sort()排序一個數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.htmlarray.sort(axis=0)按照指定軸排序一個數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html舉例import numpy as np# Sort sorts in ascending ordery = np.array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])y.sort()print(y)>>> [ 1 2 3 4 5 6 7 8 9 10]數組操作例程增加或減少元素操作描述文檔np.append(a,b)增加數據項到數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.htmlnp.insert(array, 1, 2, axis)沿著數組0軸或者1軸插入數據項https://docs.scipy.org/doc/numpy/reference/generated/numpy.insert.htmlnp.resize((2,4))將數組調整為形狀(2,4)https://docs.scipy.org/doc/numpy/reference/generated/numpy.resize.htmlnp.delete(array,1,axis)從數組裡刪除數據項https://numpy.org/doc/stable/reference/generated/numpy.delete.html舉例import numpy as np# Append items to arraya = np.array([(1, 2, 3),(4, 5, 6)])b = np.append(a, [(7, 8, 9)])print(b)>>> [1 2 3 4 5 6 7 8 9]
# Remove index 2 from previous arrayprint(np.delete(b, 2))>>> [1 2 4 5 6 7 8 9]組合數組操作描述文檔np.concatenate((a,b),axis=0)連接2個數組,添加到末尾https://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.htmlnp.vstack((a,b))按照行堆疊數組https://numpy.org/doc/stable/reference/generated/numpy.vstack.htmlnp.hstack((a,b))按照列堆疊數組docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html#numpy.hstack舉例import numpy as npa = np.array([1, 3, 5])b = np.array([2, 4, 6])
# Stack two arrays row-wiseprint(np.vstack((a,b)))>>> [[1 3 5] [2 4 6]]
# Stack two arrays column-wiseprint(np.hstack((a,b)))>>> [1 3 5 2 4 6]分割數組操作描述文檔numpy.split()分割數組
https://docs.scipy.org/doc/numpy/reference/generated/numpy.split.htmlnp.array_split(array, 3)將數組拆分為大小(幾乎)相同的子數組https://docs.scipy.org/doc/numpy/reference/generated/numpy.array_split.html#numpy.array_splitnumpy.hsplit(array, 3)在第3個索引處水平拆分數組
https://numpy.org/doc/stable/reference/generated/numpy.hsplit.html#numpy.hsplit舉例# Split array into groups of ~3a = np.array([1, 2, 3, 4, 5, 6, 7, 8])print(np.array_split(a, 3))>>> [array([1, 2, 3]), array([4, 5, 6]), array([7, 8])]數組形狀變化操作操作描述文檔other = ndarray.flatten()平鋪一個二維數組到一維數組https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.htmlnumpy.flip()翻轉一維數組中元素的順序https://docs.scipy.org/doc/stable/reference/generated/numpy.flip.htmlnp.ndarray[::-1]翻轉一維數組中元素的順序
reshape改變數組的維數https://docs.scipy.org/doc/stable/reference/generated/numpy.reshape.htmlsqueeze從數組的形狀中刪除單維度條目https://numpy.org/doc/stable/reference/generated/numpy.squeeze.htmlexpand_dims擴展數組維度
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.expand_dims.html其他操作描述文檔other = ndarray.flatten()平鋪2維數組到1維數組https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.htmlarray = np.transpose(other)
array.T數組轉置https://numpy.org/doc/stable/reference/generated/numpy.transpose.htmlinverse = np.linalg.inv(matrix)求矩陣的逆矩陣https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.inv.html
舉例>>> np.linalg.inv([[3,1],[2,4]])array([[ 0.4, -0.1], [-0.2, 0.3]])數學計算操作操作描述文檔np.add(x,y)
x + y加https://docs.scipy.org/doc/numpy/reference/generated/numpy.add.htmlnp.substract(x,y)
x - y減https://docs.scipy.org/doc/numpy/reference/generated/numpy.subtract.html#numpy.subtractnp.divide(x,y)
x / y除https://docs.scipy.org/doc/numpy/reference/generated/numpy.divide.html#numpy.dividenp.multiply(x,y)
x * y乘https://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html#numpy.multiplynp.sqrt(x)平方根https://docs.scipy.org/doc/numpy/reference/generated/numpy.sqrt.html#numpy.sqrtnp.sin(x)元素正弦https://docs.scipy.org/doc/numpy/reference/generated/numpy.sin.html#numpy.sinnp.cos(x)元素餘弦https://docs.scipy.org/doc/numpy/reference/generated/numpy.cos.html#numpy.cosnp.log(x)元素自然對數https://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html#numpy.lognp.dot(x,y)點積https://docs.scipy.org/doc/numpy/reference/generated/numpy.dot.htmlnp.roots([1,0,-4])給定多項式係數的根https://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html舉例
# If a 1d array is added to a 2d array (or the other way), NumPy# chooses the array with smaller dimension and adds it to the one# with bigger dimensiona = np.array([1, 2, 3])b = np.array([(1, 2, 3), (4, 5, 6)])print(np.add(a, b))>>> [[2 4 6] [5 7 9]] # Example of np.roots# Consider a polynomial function (x-1)^2 = x^2 - 2*x + 1# Whose roots are 1,1>>> np.roots([1,-2,1])array([1., 1.])# Similarly x^2 - 4 = 0 has roots as x=±2>>> np.roots([1,0,-4])array([-2., 2.])比較操作描述文檔==等於https://docs.python.org/2/library/stdtypes.html!=不等於
https://docs.python.org/2/library/stdtypes.html<小於https://docs.python.org/2/library/stdtypes.html>大於https://docs.python.org/2/library/stdtypes.html<=小於等於https://docs.python.org/2/library/stdtypes.html>=大於等於https://docs.python.org/2/library/stdtypes.htmlnp.array_equal(x,y)數組比較https://numpy.org/doc/stable/reference/generated/numpy.array_equal.html舉例:# Using comparison operators will create boolean NumPy arraysz = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])c = z < 6print(c)>>> [ True True True True True False False False False False]基本的統計操作描述文檔np.mean(array)Meanhttps://numpy.org/doc/stable/reference/generated/numpy.mean.html#numpy.meannp.median(array)Medianhttps://numpy.org/doc/stable/reference/generated/numpy.median.html#numpy.medianarray.corrcoef()Correlation Coefficienthttps://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html#numpy.corrcoefnp.std(array)Standard Deviationhttps://docs.scipy.org/doc/numpy/reference/generated/numpy.std.html#numpy.std舉例# Statistics of an arraya = np.array([1, 1, 2, 5, 8, 10, 11, 12])
# Standard deviationprint(np.std(a))>>> 4.2938910093294167
# Medianprint(np.median(a))>>> 6.5更多操作描述文檔array.sum()數組求和https://numpy.org/doc/stable/reference/generated/numpy.sum.htmlarray.min()數組求最小值https://numpy.org/doc/stable/reference/generated/numpy.ndarray.min.htmlarray.max(axis=0)數組求最大值(沿著0軸)
array.cumsum(axis=0)指定軸求累計和https://numpy.org/doc/stable/reference/generated/numpy.cumsum.html
切片和子集操作描述文檔array[i]索引i處的一維數組https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[i,j]索引在[i][j]處的二維數組https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[i<4]布爾索引https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[0:3]選擇索引為 0, 1和 2https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[0:2,1]選擇第0,1行,第1列https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[:1]選擇第0行數據項 (與[0:1, :]相同)https://numpy.org/doc/stable/reference/arrays.indexing.htmlarray[1:2, :]選擇第1行https://numpy.org/doc/stable/reference/arrays.indexing.html[comment]: <> "array[1,...]等同於 array[1,:,:]array[ : :-1]反轉數組同上舉例b = np.array([(1, 2, 3), (4, 5, 6)])
# The index *before* the comma refers to *rows*,# the index *after* the comma refers to *columns*print(b[0:1, 2])>>> [3]
print(b[:len(b), 2])>>> [3 6]
print(b[0, :])>>> [1 2 3]
print(b[0, 2:])>>> [3]
print(b[:, 0])>>> [1 4]
c = np.array([(1, 2, 3), (4, 5, 6)])d = c[1:2, 0:2]print(d)>>> [[4 5]]