Python科學計算 - Numpy快速入門

來源:互聯網
上載者:User

Numpy是什嗎?

Numpy是Python的一個科學計算的庫,提供了矩陣運算的功能,其一般與Scipy、matplotlib一起使用。它可用來儲存和處理大型矩陣,比Python自身的嵌套列表(nested list structure)結構要高效的多(該結構也可以用來表示矩陣(matrix))。


NumPy(Numeric Python)提供了許多進階的數值編程工具,如:矩陣資料類型、向量處理,以及精密的運算庫。專為進行嚴格的數文書處理而產生。多為很多大型金融公司使用,以及核心的科學計算群組織如:Lawrence Livermore,NASA用其處理一些本來使用C++,Fortran或Matlab等所做的任務。


多維陣列


多維陣列的類型是:numpy.ndarray


使用numpy.array方法


以list或tuple變數為參數產生一維數組:

>>> print(np.array([1,2,3,4]))[1 2 3 4]>>> print(np.array((1.2,2,3,4)))[ 1.2  2.   3.   4. ]>>> print type(np.array((1.2,2,3,4)))


以list或tuple變數為元素產生二維數組:

>>> print(np.array([[1,2],[3,4]]))[[1 2] [3 4]]


指定資料類型

例如numpy.int32, numpy.int16, and numpy.float64等:

>>> print np.array((1.2,2,3,4), dtype=np.int32)[1 2 3 4]

使用numpy.arange方法

>>> print(np.arange(15))[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14]>>> print type(np.arange(15))>>> print np.arange(15).reshape(3,5)[[ 0  1  2  3  4] [ 5  6  7  8  9] [10 11 12 13 14]]>>> print type(np.arange(15).reshape(3,5))

使用numpy.linspace方法

例如,在從1到3中產生9個數:

>>> print(np.linspace(1,3,10))[ 1.          1.22222222  1.44444444  1.66666667  1.88888889  2.11111111  2.33333333  2.55555556  2.77777778  3.        ]

構造特定的矩陣

使用numpy.zeros,numpy.ones,numpy.eye

可以構造特定的矩陣

>>> print(np.zeros((3,4)))[[ 0.  0.  0.  0.] [ 0.  0.  0.  0.] [ 0.  0.  0.  0.]]>>> print(np.ones((4,3)))[[ 1.  1.  1.] [ 1.  1.  1.] [ 1.  1.  1.] [ 1.  1.  1.]]>>> print(np.eye(4))[[ 1.  0.  0.  0.] [ 0.  1.  0.  0.] [ 0.  0.  1.  0.] [ 0.  0.  0.  1.]]

建立一個三維數組:

>>> print(np.ones((3,3,3)))[[[ 1.  1.  1.]  [ 1.  1.  1.]  [ 1.  1.  1.]] [[ 1.  1.  1.]  [ 1.  1.  1.]  [ 1.  1.  1.]] [[ 1.  1.  1.]  [ 1.  1.  1.]  [ 1.  1.  1.]]]

擷取數組的屬性

>>> a = np.zeros((2,3,2))>>> print(a.ndim)   #數組的維數3>>> print(a.shape)  #數組每一維的大小(2, 3, 2)>>> print(a.size)   #數組的元素數12>>> print(a.dtype)  #元素類型float64>>> print(a.itemsize)  #每個元素所佔的位元組數8

數組索引,切片,賦值

>>>a = np.array( [[2,3,4],[5,6,7]] )>>> print(a)[[2 3 4] [5 6 7]]>>> print(a[1,2]) #index從0開始7>>> print a[1,:][5 6 7]>>> print(a[1,1:2])[6]>>> a[1,:] = [8,9,10] #直接賦值>>> print(a)[[ 2  3  4] [ 8  9 10]]

使用for操作元素

>>> for x in np.linspace(1,3,3):...     print(x)...1.02.03.0

基本的數組運算

先構造數組a、b:

>>> a = np.ones((2,2))>>> b = np.eye(2)>>> print(a)[[ 1.  1.] [ 1.  1.]]>>> print(b)[[ 1.  0.] [ 0.  1.]]

數組的加減乘除

>>> print(a > 2)[[False False] [False False]]>>> print(a+b)[[ 2.  1.] [ 1.  2.]]>>> print(a-b)[[ 0.  1.] [ 1.  0.]]>>> print(b*2)[[ 2.  0.] [ 0.  2.]]>>> print((a*2)*(b*2))[[ 4.  0.] [ 0.  4.]]>>> print(b/(a*2))[[ 0.5  0. ] [ 0.   0.5]]>>> print((b*2)**4)[[ 16.  0] [ 0  16.]]

使用數組對象內建的方法

>>> a.sum() #a的元素個數4.0>>> a.sum(axis=0)   #計算每一列(二維數組中類似於矩陣的列)的和array([ 2.,  2.])>>> a.min()1.0>>> a.max()1.0使用numpy下的方法>>> np.sin(a)array([[ 0.84147098,  0.84147098],       [ 0.84147098,  0.84147098]])>>> np.max(a)1.0>>> np.floor(a)array([[ 1.,  1.],       [ 1.,  1.]])>>> np.exp(a)array([[ 2.71828183,  2.71828183],       [ 2.71828183,  2.71828183]])>>> np.dot(a,a)   ##矩陣乘法array([[ 2.,  2.],       [ 2.,  2.]])

合并數組

使用numpy下的vstack和hstack函數:

>>> a = np.ones((2,2))>>> b = np.eye(2)>>> print(np.vstack((a,b)))#顧名思義 v--vertical  垂直[[ 1.  1.] [ 1.  1.] [ 1.  0.] [ 0.  1.]]>>> print(np.hstack((a,b)))#顧名思義 h--horizonal 水平[[ 1.  1.  1.  0.] [ 1.  1.  0.  1.]]

看一下這兩個函數有沒有涉及到淺拷貝這種問題:

>>> c = np.hstack((a,b))>>> print c[[ 1.  1.  1.  0.] [ 1.  1.  0.  1.]]>>> a[1,1] = 5>>> b[1,1] = 5>>> print c[[ 1.  1.  1.  0.] [ 1.  1.  0.  1.]]

可以看到,a、b中元素的改變並未影響c。


深拷貝數組

數組對象內建了淺拷貝和深拷貝的方法,但是一般用深拷貝多一些:

>>> a = np.ones((2,2))>>> b = a>>> print(b is a)True>>> c = a.copy()  #深拷貝>>> c is aFalse

基本的矩陣運算

轉置:

>>> a = np.array([[1,0],[2,3]])>>> print(a)[[1 0] [2 3]]>>> print(a.transpose())[[1 2] [0 3]]

numpy.linalg關於矩陣運算的方法

>>> import numpy.linalg as nplg1

特徵值、特徵向量:

>>> print nplg.eig(a)(array([ 3.,  1.]), array([[ 0.        ,  0.70710678],       [ 1.        , -0.70710678]]))

矩陣對象

numpy模組中的矩陣對象為numpy.matrix,包括矩陣資料的處理,矩陣的計算,以及基本的統計功能,轉置,可逆性等等,包括對複數的處理,均在matrix對象中。


class numpy.matrix(data,dtype,copy):


返回一個矩陣,其中data為ndarray對象或者字元形式;


dtype:為data的type;


copy:為bool類型。

>>> a = np.matrix('1 2 7; 3 4 8; 5 6 9')>>> a             #矩陣的換行必須是用分號(;)隔開,內部資料必須為字串形式(‘ ’),矩matrix([[1, 2, 7],       #陣的元素之間必須以空格隔開。[3, 4, 8],[5, 6, 9]])>>> b=np.array([[1,5],[3,2]])>>> x=np.matrix(b)   #矩陣中的data可以為數組對象。>>> xmatrix([[1, 5],[3, 2]])

矩陣對象的屬性

matrix.T transpose

:返回矩陣的轉置矩陣


matrix.H hermitian (conjugate) transpose

:返回複數矩陣的共軛元素矩陣


matrix.I inverse

:返回矩陣的逆矩陣


matrix.A base array

:返回矩陣基於的數組


矩陣對象的方法


all([axis, out]) :沿給定的軸判斷矩陣所有元素是否為真(非0即為真)


any([axis, out]) :沿給定軸的方向判斷矩陣元素是否為真,只要一個元素為真則為真。


argmax([axis, out]) :沿給定軸的方向返回最大元素的索引(最大元素的位置).


argmin([axis, out]): 沿給定軸的方向返回最小元素的索引(最小元素的位置)


argsort([axis, kind, order]) :返回排序後的索引矩陣


astype(dtype[, order, casting, subok, copy]):將該矩陣資料複製,且資料類型為指定的資料類型


byteswap(inplace) Swap the bytes of the array elements


choose(choices[, out, mode]) :根據給定的索引得到一個新的資料矩陣(索引從choices給定)


clip(a_min, a_max[, out]) :返回新的矩陣,比給定元素大的元素為a_max,小的為a_min


compress(condition[, axis, out]) :返回滿足條件的矩陣


conj() :返回複數的共軛複數


conjugate() :返回所有複數的共軛複數元素


copy([order]) :複製一個矩陣並賦給另外一個對象,b=a.copy()


cumprod([axis, dtype, out]) :返回沿指定軸的元素累積矩陣


cumsum([axis, dtype, out]) :返回沿指定軸的元素累積和矩陣


diagonal([offset, axis1, axis2]) :返回矩陣中對角線的資料


dot(b[, out]) :兩個矩陣的點乘


dump(file) :將矩陣儲存為指定檔案,可以通過pickle.loads()或者numpy.loads()如:a.dump(‘d:\a.txt’)


dumps() :將矩陣的資料轉存為字串.


fill(value) :將矩陣中的所有元素填充為指定的value


flatten([order]) :將矩陣轉化為一個一維的形式,但是還是matrix對象


getA() :返回自己,但是作為ndarray返回


getA1():返回一個扁平(一維)的數組(ndarray)


getH() :返回自身的共軛複數轉置矩陣


getI() :返回本身的逆矩陣


getT() :返回本身的轉置矩陣


max([axis, out]) :返回指定軸的最大值


mean([axis, dtype, out]) :沿給定軸方向,返回其均值


min([axis, out]) :返回指定軸的最小值


nonzero() :返回非零元素的索引矩陣


prod([axis, dtype, out]) :返回指定軸方型上,矩陣元素的乘積.


ptp([axis, out]) :返回指定軸方向的最大值減去最小值.


put(indices, values[, mode]) :用給定的value替換矩陣本身給定索引(indices)位置的值


ravel([order]) :返回一個數組,該數組是一維數組或平數組


repeat(repeats[, axis]) :重複矩陣中的元素,可以沿指定軸方向重複矩陣元素,repeats為重複次數


reshape(shape[, order]) :改變矩陣的大小,如:reshape([2,3])


resize(new_shape[, refcheck]) :改變該資料的尺寸大小


round([decimals, out]) :返回指定精度後的矩陣,指定的位元採用四捨五入,若為1,則保留一位小數


searchsorted(v[, side, sorter]) :搜尋V在矩陣中的索引位置


sort([axis, kind, order]) :對矩陣進行排序或者按軸的方向進行排序


squeeze([axis]) :移除長度為1的軸


std([axis, dtype, out, ddof]) :沿指定軸的方向,返回元素的標準差.


sum([axis, dtype, out]) :沿指定軸的方向,返回其元素的總和


swapaxes(axis1, axis2):交換兩個軸方向上的資料.


take(indices[, axis, out, mode]) :提取指定索引位置的資料,並以一維數組或者矩陣返回(主要取決axis)


tofile(fid[, sep, format]) :將矩陣中的資料以二進位寫入到檔案


tolist() :將矩陣轉化為列表形式


tostring([order]):將矩陣轉化為python的字串.


trace([offset, axis1, axis2, dtype, out]):返回對角線元素之和


transpose(*axes) :返回矩陣的轉置矩陣,不改變原有矩陣


var([axis, dtype, out, ddof]) :沿指定軸方向,返回矩陣元素的方差


view([dtype, type]) :產生一個相同資料,但是類型為指定新類型的矩陣。


舉例

>>> a = np.asmatrix('0 2 7; 3 4 8; 5 0 9')>>> a.all()False>>> a.all(axis=0)matrix([[False, False,  True]], dtype=bool)>>> a.all(axis=1)matrix([[False],[ True],[False]], dtype=bool)

Astype方法

>>> a.astype(float)matrix([[ 12.,   3.,   5.],[ 32.,  23.,   9.],[ 10., -14.,  78.]])

Argsort方法

>>> a=np.matrix('12 3 5; 32 23 9; 10 -14 78')>>> a.argsort()matrix([[1, 2, 0],[2, 1, 0],[1, 0, 2]])

Clip方法

>>> amatrix([[ 12,   3,   5],[ 32,  23,   9],[ 10, -14,  78]])>>> a.clip(12,32)matrix([[12, 12, 12],[32, 23, 12],[12, 12, 32]])


Cumprod方法

 >>> a.cumprod(axis=1)matrix([[    12,     36,    180],[    32,    736,   6624],[    10,   -140, -10920]])

Cumsum方法

>>> a.cumsum(axis=1)matrix([[12, 15, 20],[32, 55, 64],[10, -4, 74]])


Tolist方法

>>> b.tolist()[[12, 3, 5], [32, 23, 9], [10, -14, 78]]

Tofile方法

>>> b.tofile('d:\\b.txt')

compress()方法

>>> from numpy import *

>>> a = array([10, 20, 30, 40])>>> condition = (a > 15) & (a < 35)>>> conditionarray([False, True, True, False], dtype=bool)>>> a.compress(condition)array([20, 30])>>> a[condition]                                      # same effectarray([20, 30])>>> compress(a >= 30, a)                              # this form aso existsarray([30, 40])>>> b = array([[10,20,30],[40,50,60]])>>> b.compress(b.ravel() >= 22)array([30, 40, 50, 60])>>> x = array([3,1,2])>>> y = array([50, 101])>>> b.compress(x >= 2, axis=1)                       # illustrates the use of the axis keywordarray([[10, 30],[40, 60]])>>> b.compress(y >= 100, axis=0)array([[40, 50, 60]])
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.