首頁 後端開發 Python教學 Python科學計算 - Numpy快速入門

Python科學計算 - Numpy快速入門

Oct 17, 2016 pm 01:41 PM

Numpy是什麼?

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


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


多維數組


多維數組的型別是:numpy.ndarray


使用numpy.ndarray


使用numpy.arraple.arraple

>>> 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)))
<type &#39;numpy.ndarray&#39;>
登入後複製

   


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

>>> print(np.array([[1,2],[3,4]]))
[[1 2]
 [3 4]]
登入後複製


.

>>> 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))
<type &#39;numpy.ndarray&#39;>
>>> 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))
<type &#39;numpy.ndarray&#39;>
登入後複製

   

使用numpy.linspace方法

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

可以構造特定的矩陣

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

創建一個三維陣列:

>>> 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.]]]
登入後複製

   

使用for操作元素

>>> 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
登入後複製

   

rro

數組的加減乘除

>>>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 x in np.linspace(1,3,3):
...     print(x)
...
1.0
2.0
3.0
登入後複製

   

合併數組

使用numpy下的vstack和hstack函數:

>>> 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、b中元素的變化並未影響c。

深拷貝數組

數組物件自帶了淺拷貝和深拷貝的方法,但是一般用深拷貝多一些:

>>> 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.linalg關於矩陣運算的方法

>>> 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.]]
登入後複製

 矩陣資料的處理,矩陣的計算,以及基本的統計功能,轉置,可逆性等等,包括複數的處理,皆在matrix物件中。

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


回傳一個矩陣,其中data為ndarray物件或字元形式;

copy:為bool型。

>>> a = np.ones((2,2))
>>> b = a
>>> print(b is a)
True
>>> c = a.copy()  #深拷贝
>>> c is a
False
登入後複製

   

矩陣對象的屬性

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[, subok, sub , copy]):將該矩陣資料複製,且資料型別為指定的資料型別

byteswap(inplace) Swap the bytes of the array elements

:根據給定的索引得到一個新的資料矩陣(索引從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(&#39;0 2 7; 3 4 8; 5 0 9&#39;)
>>> 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(&#39;12 3 5; 32 23 9; 10 -14 78&#39;)
>>> a.argsort()
matrix([[1, 2, 0],
[2, 1, 0],
[1, 0, 2]])
登入後複製

Clip方法

>>> a
matrix([[ 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(&#39;d:\\b.txt&#39;)
登入後複製

compress()方法

>>> from numpy import *

>>> a = array([10, 20, 30, 40])
>>> condition = (a > 15) & (a < 35)
>>> condition
array([False, True, True, False], dtype=bool)
>>> a.compress(condition)
array([20, 30])
>>> a[condition]                                      # same effect
array([20, 30])
>>> compress(a >= 30, a)                              # this form a
so exists
array([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 keyword
array([[10, 30],
[40, 60]])
>>> b.compress(y >= 100, axis=0)
array([[40, 50, 60]])
登入後複製

   


本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

如何解決Linux終端中查看Python版本時遇到的權限問題? 如何解決Linux終端中查看Python版本時遇到的權限問題? Apr 01, 2025 pm 05:09 PM

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到? 如何在使用 Fiddler Everywhere 進行中間人讀取時避免被瀏覽器檢測到? Apr 02, 2025 am 07:15 AM

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中? 在Python中如何高效地將一個DataFrame的整列複製到另一個結構不同的DataFrame中? Apr 01, 2025 pm 11:15 PM

在使用Python的pandas庫時,如何在兩個結構不同的DataFrame之間進行整列複製是一個常見的問題。假設我們有兩個Dat...

Uvicorn是如何在沒有serve_forever()的情況下持續監聽HTTP請求的? Uvicorn是如何在沒有serve_forever()的情況下持續監聽HTTP請求的? Apr 01, 2025 pm 10:51 PM

Uvicorn是如何持續監聽HTTP請求的? Uvicorn是一個基於ASGI的輕量級Web服務器,其核心功能之一便是監聽HTTP請求並進�...

如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎? 如何在10小時內通過項目和問題驅動的方式教計算機小白編程基礎? Apr 02, 2025 am 07:18 AM

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

在Linux終端中使用python --version命令時如何解決權限問題? 在Linux終端中使用python --version命令時如何解決權限問題? Apr 02, 2025 am 06:36 AM

Linux終端中使用python...

如何繞過Investing.com的反爬蟲機制獲取新聞數據? 如何繞過Investing.com的反爬蟲機制獲取新聞數據? Apr 02, 2025 am 07:03 AM

攻克Investing.com的反爬蟲策略許多人嘗試爬取Investing.com(https://cn.investing.com/news/latest-news)的新聞數據時,常常�...

See all articles