python中numpy的矩陣、多維陣列的用法,pythonnumpy

來源:互聯網
上載者:User

python中numpy的矩陣、多維陣列的用法,pythonnumpy

1. 引言

最近在將一個演算法由matlab轉成python,初學python,很多地方還不熟悉,總體感覺就是上手容易,實際上很優雅地用python還是蠻難的。目前為止,覺得就演算法模擬研究而言,還是matlab用得特別舒服,可能是比較熟悉的緣故吧。matlab直接整合了很多演算法工具箱,函數查詢、調用、變數查詢等非常方便,或許以後用久了python也會感覺很好用。與python相比,最喜歡的莫過於可以直接選中某段代碼執行了,操作方便,python也可以實現,就是感覺不是很方便。

言歸正傳,做演算法要用到很多的向量和矩陣運算操作,這些嘛在matlab裡面已經很熟悉了,但用python的時候需要用一個查一個,挺煩的,所以在此稍作總結,後續使用過程中會根據使用體驗更新。

python的矩陣運算主要依賴numpy包,scipy包以numpy為基礎,大大擴充了後者的運算能力。

2. 建立一般的多維陣列

import numpy as npa = np.array([1,2,3], dtype=int) # 建立1*3維數組 array([1,2,3])type(a) # numpy.ndarray類型a.shape # 維數資訊(3L,)a.dtype.name # 'int32'a.size # 元素個數:3a.itemsize #每個元素所佔用的位元組數目:4b=np.array([[1,2,3],[4,5,6]],dtype=int) # 建立2*3維數組 array([[1,2,3],[4,5,6]])b.shape # 維數資訊(2L,3L)b.size # 元素個數:6b.itemsize # 每個元素所佔用的位元組數目:4c=np.array([[1,2,3],[4,5,6]],dtype='int16') # 建立2*3維數組 array([[1,2,3],[4,5,6]],dtype=int16)c.shape # 維數資訊(2L,3L)c.size # 元素個數:6c.itemsize # 每個元素所佔用的位元組數目:2c.ndim # 維數 d=np.array([[1,2,3],[4,5,6]],dtype=complex) # 複數二維數組d.itemsize # 每個元素所佔用的位元組數目:16d.dtype.name # 元素類型:'complex128'

3. 建立特殊類型的多維陣列 

a1 = np.zeros((3,4)) # 建立3*4全零二維數組輸出:array([[ 0., 0., 0., 0.],  [ 0., 0., 0., 0.],  [ 0., 0., 0., 0.]])a1.dtype.name # 元素類型:'float64'a1.size # 元素個數:12a1.itemsize # 每個元素所佔用的位元組個數:8  a2 = np.ones((2,3,4), dtype=np.int16) # 建立2*3*4全1三維數組a2 = np.ones((2,3,4), dtype='int16')  # 建立2*3*4全1三維數組輸出:array([[[1, 1, 1, 1],  [1, 1, 1, 1],  [1, 1, 1, 1]],   [[1, 1, 1, 1],  [1, 1, 1, 1],  [1, 1, 1, 1]]], dtype=int16)  a3 = np.empty((2,3)) # 建立2*3的未初始化二維數組輸出:(may vary)array([[ 1., 2., 3.],  [ 4., 5., 6.]])a4 = np.arange(10,30,5) # 初始值10,結束值:30(不包含),步長:5輸出:array([10, 15, 20, 25])a5 = np.arange(0,2,0.3) # 初始值0,結束值:2(不包含),步長:0.2輸出:array([ 0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])from numpy import pinp.linspace(0, 2, 9) # 初始值0,結束值:2(包含),元素個數:9輸出:array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])x = np.linspace(0, 2*pi, 9)輸出:array([ 0.  , 0.78539816, 1.57079633, 2.35619449, 3.14159265,  3.92699082, 4.71238898, 5.49778714, 6.28318531])a = np.arange(6)輸出:array([0, 1, 2, 3, 4, 5])b = np.arange(12).reshape(4,3)輸出:array([[ 0, 1, 2],  [ 3, 4, 5],  [ 6, 7, 8],  [ 9, 10, 11]])c = np.arange(24).reshape(2,3,4)輸出: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]]])  

使用numpy.set_printoptions可以設定numpy變數的列印格式

在ipython環境下,使用help(numpy.set_printoptions)查詢使用協助和樣本

4. 多維陣列的基本操作

加法和減法操作要求操作雙方的維數資訊一致,均為M*N為數組方可正確執行操作。

a = np.arange(4)輸出:array([0, 1, 2, 3])b = a**2輸出:array([0, 1, 4, 9])c = 10*np.sin(a)輸出: array([ 0.  , 8.41470985, 9.09297427, 1.41120008])  n < 35輸出:array([ True, True, True, True], dtype=bool) A = np.array([[1,1],[0,1]])B = np.array([[2,0],[3,4]])C = A * B # 元素點乘輸出:array([[2, 0],  [0, 4]])D = A.dot(B) # 矩陣乘法輸出:array([[5, 4],  [3, 4]])E = np.dot(A,B) # 矩陣乘法輸出:array([[5, 4],  [3, 4]])

多維陣列操作過程中的類型轉換

When operating with arrays of different types, the type of the resulting array corresponds to the more general or precise one (a behavior known as upcasting)

即操作不同類型的多維陣列時,結果自動轉換為精度更高類型的數組,即upcasting

a = np.ones((2,3),dtype=int)  # int32b = np.random.random((2,3))  # float64b += a # 正確 a += b # 錯誤 
a = np.ones(3,dtype=np.int32)b = np.linspace(0,pi,3)c = a + bd = np.exp(c*1j)輸出:array([ 0.54030231+0.84147098j, -0.84147098+0.54030231j,  -0.54030231-0.84147098j])d.dtype.name輸出: 'complex128' 

多維陣列的一元操作,如求和、求最小值、最大值等

a = np.random.random((2,3))a.sum()a.min()a.max()  b = np.arange(12).reshape(3,4)輸出:array([[ 0, 1, 2, 3],  [ 4, 5, 6, 7],  [ 8, 9, 10, 11]])b.sum(axis=0) # 按列求和輸出:array([12, 15, 18, 21])b.sum(axis=1) # 按行求和輸出:array([ 6, 22, 38])b.cumsum(axis=0) # 按列進行元素累加輸出:array([[ 0, 1, 2, 3],  [ 4, 6, 8, 10],  [12, 15, 18, 21]])b.cumsum(axis=1) # 按行進行元素累加輸出:array([[ 0, 1, 3, 6],  [ 4, 9, 15, 22],  [ 8, 17, 27, 38]]) universal functionsB = np.arange(3)np.exp(B)np.sqrt(B)C = np.array([2.,-1.,4.])np.add(B,C) 

其他的ufunc函數包括:

all, any, apply_along_axis, argmax, argmin, argsort, average, bincount, ceil, clip, conj, corrcoef, cov, cross, cumprod, cumsum, diff, dot, floor,inner, lexsort, max, maximum, mean, median, min, minimum, nonzero, outer, prod, re, round, sort, std, sum, trace, transpose, var,vdot, vectorize, where

5. 數組索引、切片和迭代

a = np.arange(10)**3a[2]a[2:5]a[::-1] # 逆序輸出for i in a: print (i**(1/3.)) 
def f(x,y): return 10*x+yb = np.fromfunction(f,(5,4),dtype=int)b[2,3]b[0:5,1]b[:,1]b[1:3,:]b[-1] 
c = np.array([[[0,1,2],[10,11,12]],[[100,101,102],[110,111,112]]])輸出:array([[[ 0, 1, 2],  [ 10, 11, 12]],   [[100, 101, 102],  [110, 111, 112]]])c.shape輸出:(2L, 2L, 3L)c[0,...]c[0,:,:]輸出:array([[ 0, 1, 2],  [10, 11, 12]])c[:,:,2]c[...,2]輸出:array([[ 2, 12],  [102, 112]]) for row in c: print(row) for element in c.flat: print(element) 
a = np.floor(10*np.random.random((3,4)))輸出:array([[ 3., 9., 8., 4.],  [ 2., 1., 4., 6.],  [ 0., 6., 0., 2.]])a.ravel()輸出:array([ 3., 9., 8., ..., 6., 0., 2.])a.reshape(6,2)輸出:array([[ 3., 9.],  [ 8., 4.],  [ 2., 1.],  [ 4., 6.],  [ 0., 6.],  [ 0., 2.]])a.T輸出:array([[ 3., 2., 0.],  [ 9., 1., 6.],  [ 8., 4., 0.],  [ 4., 6., 2.]])a.T.shape輸出:(4L, 3L)a.resize((2,6))輸出:array([[ 3., 9., 8., 4., 2., 1.],  [ 4., 6., 0., 6., 0., 2.]])a.shape輸出:(2L, 6L)a.reshape(3,-1)輸出:array([[ 3., 9., 8., 4.],  [ 2., 1., 4., 6.],  [ 0., 6., 0., 2.]]) 

詳查以下函數:

ndarray.shape, reshape, resize, ravel

6. 組合不同的多維陣列

a = np.floor(10*np.random.random((2,2)))輸出:array([[ 5., 2.],  [ 6., 2.]])b = np.floor(10*np.random.random((2,2)))輸出:array([[ 0., 2.],  [ 4., 1.]])np.vstack((a,b))輸出:array([[ 5., 2.],  [ 6., 2.],  [ 0., 2.],  [ 4., 1.]])np.hstack((a,b))輸出:array([[ 5., 2., 0., 2.],  [ 6., 2., 4., 1.]])  from numpy import newaxisnp.column_stack((a,b))輸出:array([[ 5., 2., 0., 2.],  [ 6., 2., 4., 1.]])  a = np.array([4.,2.])b = np.array([2.,8.])a[:,newaxis]輸出:array([[ 4.],  [ 2.]])b[:,newaxis]輸出:array([[ 2.],  [ 8.]])np.column_stack((a[:,newaxis],b[:,newaxis]))輸出:array([[ 4., 2.],  [ 2., 8.]])np.vstack((a[:,newaxis],b[:,newaxis]))輸出:array([[ 4.],  [ 2.],  [ 2.],  [ 8.]])np.r_[1:4,0,4]輸出:array([1, 2, 3, 0, 4])np.c_[np.array([[1,2,3]]),0,0,0,np.array([[4,5,6]])]輸出:array([[1, 2, 3, 0, 0, 0, 4, 5, 6]]) 

詳細使用請查詢以下函數:

hstack, vstack, column_stack, concatenate, c_, r_

7. 將較大的多維陣列分割成較小的多維陣列

a = np.floor(10*np.random.random((2,12)))輸出:array([[ 9., 7., 9., ..., 3., 2., 4.],  [ 5., 3., 3., ..., 9., 7., 7.]])np.hsplit(a,3)輸出:[array([[ 9., 7., 9., 6.],  [ 5., 3., 3., 1.]]), array([[ 7., 2., 1., 6.],  [ 7., 5., 0., 2.]]), array([[ 9., 3., 2., 4.],  [ 3., 9., 7., 7.]])]np.hsplit(a,(3,4))輸出:[array([[ 9., 7., 9.],  [ 5., 3., 3.]]), array([[ 6.],  [ 1.]]), array([[ 7., 2., 1., ..., 3., 2., 4.],  [ 7., 5., 0., ..., 9., 7., 7.]])] 

實作類別似功能的函數包括:

hsplit,vsplit,array_split

8.  多維陣列的複製操作

a = np.arange(12)輸出:array([ 0, 1, 2, ..., 9, 10, 11]) not copy at all b = ab is a # Trueb.shape = 3,4a.shape # (3L,4L) def f(x) # Python passes mutable objects as references, so function calls make no copy. print(id(x)) # id是python對象的唯一識別碼 id(a) # 111833936Lid(b) # 111833936Lf(a)  # 111833936L  淺複製c = a.view()c is a # Falsec.base is a # Truec.flags.owndata # Falsec.shape = 2,6a.shape # (3L,4L)c[0,4] = 1234print(a)輸出:array([[ 0, 1, 2, 3],  [1234, 5, 6, 7],  [ 8, 9, 10, 11]])s = a[:,1:3]s[:] = 10print(a)輸出:array([[ 0, 10, 10, 3],  [1234, 10, 10, 7],  [ 8, 10, 10, 11]])  深複製d = a.copy()d is a # Falsed.base is a # Falsed[0,0] = 9999print(a)輸出:array([[ 0, 10, 10, 3],  [1234, 10, 10, 7],  [ 8, 10, 10, 11]]) 

numpy基本函數和方法一覽

arange, array, copy, empty, empty_like, eye, fromfile, fromfunction, identity, linspace, logspace, mgrid, ogrid, ones, ones_like, r, zeros,zeros_like

Conversions

ndarray.astype, atleast_1d, atleast_2d, atleast_3d, mat

Manipulations

array_split, column_stack, concatenate, diagonal, dsplit, dstack, hsplit, hstack, ndarray.item, newaxis, ravel, repeat, reshape, resize,squeeze, swapaxes, take, transpose, vsplit, vstack

Questionsall, any, nonzero, where

Ordering

argmax, argmin, argsort, max, min, ptp, searchsorted, sort

Operations

choose, compress, cumprod, cumsum, inner, ndarray.fill, imag, prod, put, putmask, real, sum

Basic Statistics

cov, mean, std, var

Basic Linear Algebra

cross, dot, outer, linalg.svd, vdot

完整的函數和方法一覽錶鏈接:

https://docs.scipy.org/doc/numpy-dev/reference/routines.html#routines

9. 特殊的索引技巧

a = np.arange(12)**2輸出:array([ 0, 1, 4, ..., 81, 100, 121])i = np.array([1,1,3,8,5])a[i]輸出:array([ 1, 1, 9, 64, 25])j = np.array([[3,4],[9,7]])a[j]輸出:array([[ 9, 16],  [81, 49]])palette = np.array([[0,0,0],[255,0,0],[0,255,0],[0,0,255],[255,255,255]])image = np.array([[0,1,2,0],[0,3,4,0]])palette[image]輸出:array([[[ 0, 0, 0],  [255, 0, 0],  [ 0, 255, 0],  [ 0, 0, 0]],  [[ 0, 0, 0],  [ 0, 0, 255],  [255, 255, 255],  [ 0, 0, 0]]])i = np.array([[0,1],[1,2]])j = np.array([[2,1],[3,3]])a[i,j]輸出:array([[ 2, 5],  [ 7, 11]])l = [i,j]a[l]輸出:array([[ 2, 5],  [ 7, 11]])a[i,2]輸出:array([[ 2, 6],  [ 6, 10]])a[:,j]輸出:array([[[ 2, 1],  [ 3, 3]],  [[ 6, 5],  [ 7, 7]],  [[10, 9],  [11, 11]]])
s = np.array([i,j])print(s)array([[[0, 1],  [1, 2]],  [[2, 1],  [3, 3]]])a[tuple(s)]輸出:array([[ 2, 5],  [ 7, 11]])print(tupe(s))輸出:(array([[0, 1],  [1, 2]]), array([[2, 1],  [3, 3]]))

10. 尋找最大值/最小值及其對應索引值

time = np.linspace(20, 145, 5)輸出: array([ 20. , 51.25, 82.5 , 113.75, 145. ])data = np.sin(np.arange(20)).reshape(5,4)輸出:array([[ 0.  , 0.84147098, 0.90929743, 0.14112001],  [-0.7568025 , -0.95892427, -0.2794155 , 0.6569866 ],  [ 0.98935825, 0.41211849, -0.54402111, -0.99999021],  [-0.53657292, 0.42016704, 0.99060736, 0.65028784],  [-0.28790332, -0.96139749, -0.75098725, 0.14987721]])ind = data.argmax(axis=0)輸出:array([2, 0, 3, 1], dtype=int64)time_max = time[ind]輸出:array([ 82.5 , 20. , 113.75, 51.25])data_max = data[ind, xrange(data.shape[1])]輸出:array([ 0.98935825, 0.84147098, 0.99060736, 0.6569866 ])np.all(data_max == data.max(axis=0))輸出:True a = np.arange(5)a[[1,3,4]] = 0print(a)輸出:array([0, 0, 2, 0, 0])
a = np.arange(5)a[[0,0,2]] = [1,2,3]print(a)輸出:array([2, 1, 3, 3, 4])a = np.arange(5)a[[0,0,2]] += 1print(a)輸出:array([1, 1, 3, 3, 4])
a = np.arange(12).reshape(3,4) b = a > 4輸出:array([[False, False, False, False],  [False, True, True, True],  [ True, True, True, True]], dtype=bool)a[b]輸出:array([ 5, 6, 7, 8, 9, 10, 11])a[b] = 0print(a)輸出:array([[0, 1, 2, 3],  [4, 0, 0, 0],  [0, 0, 0, 0]])
a = np.arange(12).reshape(3,4)b1 = np.array([False,True,True])b2 = n.array([True,False,True,False])a[b1,:]輸出:array([[ 4, 5, 6, 7],  [ 8, 9, 10, 11]])a[b1]輸出:array([[ 4, 5, 6, 7],  [ 8, 9, 10, 11]])a[:,b2]輸出:array([[ 0, 2],  [ 4, 6],  [ 8, 10]])a[b1,b2]輸出:array([ 4, 10])

11. ix_() function

a = np.array([2,3,4,5])b = np.array([8,5,4])c = np.array([5,4,6,8,3])ax,bx,cx = np.ix_(a,b,c)print(ax) # (4L, 1L, 1L)輸出:array([[[2]],  [[3]],  [[4]],  [[5]]])print(bx) # (1L, 3L, 1L)輸出:array([[[8],  [5],  [4]]])print(cx) # (1L, 1L, 5L)輸出:array([[[5, 4, 6, 8, 3]]])result = ax + bx*cx輸出:array([[[42, 34, 50, 66, 26],  [27, 22, 32, 42, 17],  [22, 18, 26, 34, 14]],  [[43, 35, 51, 67, 27],  [28, 23, 33, 43, 18],  [23, 19, 27, 35, 15]],  [[44, 36, 52, 68, 28],  [29, 24, 34, 44, 19],  [24, 20, 28, 36, 16]],  [[45, 37, 53, 69, 29],  [30, 25, 35, 45, 20],  [25, 21, 29, 37, 17]]])result[3,2,4]輸出:17

12. 線性代數運算

a = np.array([[1.,2.],[3.,4.]])a.transpose() # 轉置np.linalg.inv(a) # 求逆u = np.eye(2) # 產生單位矩陣np.dot(a,a) # 矩陣乘積np.trace(a) # 求矩陣的跡y = np.array([5.],[7.]])np.linalg.solve(a,y) # 求解線性方程組np.linalg.eig(a) # 特徵分解

“Automatic” Reshaping

a = np.arange(30)a.shape = 2,-1,3a.shape # (2L, 5L, 3L)print(a)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],  [24, 25, 26],  [27, 28, 29]]])
x = np.arange(0,10,2)y = np.arange(5)m = np.vstack([x,y])輸出:array([[0, 2, 4, 6, 8],  [0, 1, 2, 3, 4]])n = np.hstack([x,y])輸出:array([0, 2, 4, 6, 8, 0, 1, 2, 3, 4])

13. 矩陣的建立

a = np.array([1,2,3])a1 = np.mat(a)輸出:matrix([[1, 2, 3]])type(a1)輸出:numpy.matrixlib.defmatrix.matrixa1.shape輸出:(1L, 3L)a.shape輸出:(3L,)b=np.matrix([1,2,3])輸出:matrix([[1, 2, 3]])from numpy import *data1 = mat(zeros((3,3)))data2 = mat(ones((2,4)))data3 = mat(random.rand(2,2))data4 = mat(random.randint(2,8,size=(2,5)))data5 = mat(eye(2,2,dtype=int))

14. 常見的矩陣運算

a1 = mat([1,2])a2 = mat([[1],[2]])a3 = a1 * a2print(a3)輸出:matrix([[5]])print(a1*2)輸出:matrix([[2, 4]])a1 = mat(eye(2,2)*0.5)print(a1.I)輸出:matrix([[ 2., 0.],  [ 0., 2.]])a1 = mat([[1,2],[2,3],[4,2]])a1.sum(axis=0)輸出:matrix([[7, 7]])a1.sum(axis=1)輸出:matrix([[3],  [5],  [6]])a1.max() # 求矩陣元素最大值輸出:4a1.min() # 求矩陣元素最小值輸出:1np.max(a1,0) # 求矩陣每列元素最大值輸出:matrix([[4, 3]])np.max(a1,1) # 求矩陣每行元素最大值輸出:matrix([[2],  [3],  [4]])a = mat(ones((2,2)))b = mat(eye((2)))c = hstack((a,b))輸出:matrix([[ 1., 1., 1., 0.],  [ 1., 1., 0., 1.]])d = vstack((a,b))輸出:matrix([[ 1., 1.],  [ 1., 1.],  [ 1., 0.],  [ 0., 1.]])

15. 矩陣、數組、列表之間的互相轉換

aa = [[1,2],[3,4],[5,6]]bb = array(aa)cc = mat(bb)cc.getA() # 矩陣轉換為數組cc.tolist() # 矩陣轉換為列表bb.tolist() # 數群組轉換為列表# 當列表為一維時,情況有點特殊aa = [1,2,3,4]bb = array(aa)輸出:array([1, 2, 3, 4])cc = mat(bb)輸出:matrix([[1, 2, 3, 4]])cc.tolist()輸出:[[1, 2, 3, 4]]bb.tolist()輸出:[1, 2, 3, 4]cc.tolist()[0]輸出:[1, 2, 3, 4]

內容整理參考連結如下:

https://docs.scipy.org/doc/numpy-dev/user/quickstart.html

http://python.usyiyi.cn/translate/NumPy_v111/reference/arrays.scalars.html#arrays-scalars-built-in

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.