20.1 NumPy介紹
NumPy是Python的一種開源的數(shù)值計算擴展庫耕漱。它包含很多功能:
創(chuàng)建n維數(shù)組(矩陣)
對數(shù)組進行函數(shù)運算
數(shù)值積分
線性代數(shù)運算
傅里葉變換
-
隨機數(shù)產(chǎn)生
······
NumPy是在1995年誕生的Python庫Numeric的基礎(chǔ)上建立起來的阳谍。但真正促使NumPy的發(fā)行的是Python的SciPy庫叶撒。
-
SciPy是2001年發(fā)行的一個類似于Matlab,Maple啄枕,Mathematica等數(shù)學(xué)計算軟件的Python庫萌抵,它實現(xiàn)里面的大多數(shù)功能稿饰。
NumPy提供了兩種基本的對象:
ndarray:全稱(n-dimensional array object)是儲存單一數(shù)據(jù)類型的多維數(shù)組缰儿。
ufunc:全稱(universal function object)它是一種能夠?qū)?shù)組進行處理的函數(shù)畦粮。
NumPy的官方文檔:
https://docs.scipy.org/doc/numpy/reference/-
ndarray 對象
- ndarray的創(chuàng)建
- ndarray的屬性
- ndarray的切片
- 多維數(shù)組
- 結(jié)構(gòu)數(shù)組
20.1.1 Ndarray的創(chuàng)建
- NumPy中的核心對象是ndarray。
- ndarray可以看成數(shù)組乖阵,類似于R語言的向量或者矩陣宣赔。
- NumPy里面所有的函數(shù)都是圍繞ndarray展開的。
- ndarray對維數(shù)沒有限制瞪浸。
- [ ]從內(nèi)到外分別為第0軸儒将,第1軸,第2軸对蒲。
- c第0軸長度為3钩蚊,第1軸長度為4。
-
NumPy提供了專門用于生成ndarray的函數(shù)齐蔽,提高創(chuàng)建ndarray的速度。
- 還可以自定義函數(shù)產(chǎn)生ndarray床估。
- fromfunction第一個參數(shù)接收計算函數(shù)含滴,第二個參數(shù)接收數(shù)組的形狀。
20.1.2 Ndarray的屬性
- ndarray的元素具有相同的元素類型丐巫。常用的有int(整型)谈况,float(浮點型)勺美,complex(復(fù)數(shù)型)。
- ndarray的shape屬性用來獲得它的形狀碑韵,也可以自己指定赡茸。
20.1.3 Ndarray切片
- ndarray的切片和list是一樣的。
- 可以通過切片的對ndarray中的元素進行更改祝闻。
- ndarray通過切片產(chǎn)生一個新的數(shù)組b占卧,b和a共享同一塊數(shù)據(jù)存儲空間。
- 如果想改變這種情況联喘,我們可以用列表對數(shù)組元素切片华蜒。
20.1.4 多維數(shù)組
- NumPy的多維數(shù)組和一維數(shù)組類似。多維數(shù)組有多個軸豁遭。
- 我們前面已經(jīng)提到從內(nèi)到外分別是第0軸叭喜,第1軸…
-
如果我們想創(chuàng)立原數(shù)組的副本,我們可以用整數(shù)元組蓖谢,列表捂蕴,整數(shù)數(shù)組,布爾數(shù)組進行切片
20.1.5 結(jié)構(gòu)數(shù)組
- C語言中可以通過struct關(guān)鍵字定義結(jié)構(gòu)類型闪幽。
- NumPy中也有類似的結(jié)構(gòu)數(shù)組啥辨。
20.2 Ufunc函數(shù)
20.2.1 Ufunc簡介
- ufunc是universal function的簡稱,它是一種能對數(shù)組每個元素進行運算的函數(shù)沟使。
- 值得注意的是委可,對于同等長度的ndarray,np.sin()比math.sin()快
- 但是對于單個數(shù)值腊嗡,math.sin()的速度則更快着倾。
20.2.2 四則運算
-
NumPy提供了許多ufunc函數(shù),它們和相應(yīng)的運算符運算結(jié)果相同燕少。
20.2.3 比較運算和布爾運算
- 使用==卡者,>對兩個數(shù)組進行比較,會返回一個布爾數(shù)組客们,每一個元素都是對應(yīng)元素的比較結(jié)果崇决。
-
布爾運算在NumPy中也有對應(yīng)的ufunc函數(shù)。
20.2.4 自定義ufunc函數(shù)
- NumPy提供的標準ufunc函數(shù)可以組合出復(fù)合的表達式底挫,但是有些情況下恒傻,自己編寫的則更為方便。
- 我們可以把自己編寫的函數(shù)用frompyfunc()轉(zhuǎn)化成ufunc函數(shù)建邓。
- 使用frompyfunc()進行轉(zhuǎn)化
- func:計算函數(shù)
- nin:func()輸入?yún)?shù)的個數(shù)
- nout:func()輸出參數(shù)的個數(shù)
- 因為最后輸出的元素類型是object盈厘,所以我們還需要把它轉(zhuǎn)換成整型。
20.2.5 廣播(broadcasting)
- 使用ufunc對兩個數(shù)組進行運算時官边,ufunc函數(shù)會對兩個數(shù)組的對應(yīng)元素進行運算沸手。如果數(shù)組的形狀不相同外遇,就會進行下廣播處理。
-
簡而言之契吉,就是向兩個數(shù)組每一維度上的最大值靠齊
20.3 隨機數(shù)
-
NumPy產(chǎn)生隨機數(shù)的模塊在random里面跳仿,其中有大量的分布。
20.4 求和捐晶、平均值菲语、方差
-
NumPy在均值等方面常用的函數(shù)如下:
- keepdims可以保持原來數(shù)組的維數(shù)。
20.5 大小與排序
-
NumPy在排序等方面常用的函數(shù)如下:
- min,max都有axis,out,keepdims等參數(shù)
- sort()對數(shù)組進行排序會改變數(shù)組的內(nèi)容租悄,返回一個新的數(shù)組谨究。
- percentile計算處于p%上的值。
20.5 統(tǒng)計函數(shù)
- NumPy中常用的統(tǒng)計函數(shù)有:unique(), bicount(), histogram()泣棋。
- unique有兩個參數(shù),return_index=True同時返回原始數(shù)組中的下 - 標,return_inverse=True表示原始數(shù)據(jù)在新數(shù)組的下標胶哲。
- bincount()對非負整數(shù)數(shù)組中的各個元素出現(xiàn)的次數(shù)進行統(tǒng)計,返回數(shù)組中的第i個元素是整數(shù)i出現(xiàn)的次數(shù)潭辈。
- histogram()對以為數(shù)組進行直方圖統(tǒng)計鸯屿,其參數(shù)為:
- histogram(a, bins=10, range=None, weights=None)函數(shù)返回兩個一維數(shù)組,hist是每個區(qū)間的統(tǒng)計結(jié)果, bin_edges返回區(qū)間的邊界值把敢。
20.6 操作多維數(shù)組
- 多維數(shù)組可以進行連接寄摆,分段等多種操作。
- vstack()函數(shù)
- hstack()函數(shù)
- column_stack()函數(shù)修赞。
- split()函數(shù)進行分段婶恼。
20.7 多項式函數(shù)
- 多項式也可以進行積分和求導(dǎo)。
- Roots可以求多項式的根柏副。
- polyfit()可以對數(shù)據(jù)進行多項式擬合勾邦。x, y為數(shù)據(jù)點,deg為多項式最高階數(shù)割择。
- poly()返回多項式系數(shù)構(gòu)成的數(shù)組眷篇。
20.8 實驗
In:
import numpy as np
數(shù)組創(chuàng)建
In:
a1 = np.array([1,2,3])
In:
a1.shape
out:
(3,)
In:
a2 = np.array([[1,2,3],[4,5,6]])
a2.shape
out:
(2, 3)
In:
a3 = np.arange(0,10,1)
a3
out:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In:
np.linspace(0,10,5)
out:
array([ 0. , 2.5, 5. , 7.5, 10. ])
In:
np.zeros(10)
out:
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In:
a3.dtype
out:
dtype('int32')
In:
a2.reshape(3,2)
out:
array([[1, 2],
[3, 4],
[5, 6]])
UFUNC
In:
np.greater_equal(np.array([1,2,3]),np.array([0,0,6]))
out:
array([ True, True, False])
In:
a3.dtype
out:
dtype('int32')
In:
a4 = a3.astype(np.float)
a4.dtype
out:
dtype('float64')
隨機數(shù)
In:
np.random.randint(5,size=10) #5是范圍
out:
array([3, 3, 2, 4, 4, 1, 2, 1, 1, 1])
In:
np.random.normal(0,1,100) #正太分布,均值為0荔泳,方差為1蕉饼,100個數(shù)
out:
array([-0.80861078, -2.07749691, 0.29377679, -1.96900312, -1.25783093,
-0.99607882, -0.87248032, -2.26714699, 1.30187567, 0.10194601,
-0.42405655, -1.59441604, -2.31300876, 0.69700842, -0.65660689,
0.01491257, 0.24889131, 0.3133219 , 1.09196143, -2.45041751,
-0.71471691, -0.26187846, -1.93342864, -0.21497748, -0.20100491,
-0.73638216, 1.08467604, 0.53403982, -0.03887703, 1.12471892,
0.78003454, 0.44594115, -0.17300147, -0.09442446, -0.93177358,
1.71758462, 0.88627094, 0.70998374, -1.06083069, 0.28917184,
0.62578472, -1.35847831, -0.82151136, -2.50524439, 0.13409251,
1.95447607, -0.66078128, -0.54954445, 0.18099372, 0.63007529,
-0.32250372, 0.19161832, -0.03845566, 1.42156815, -0.60922562,
0.35661966, -0.94926617, -0.07052227, 1.28500753, 0.83647684,
-0.08366194, -0.07888412, -0.75984669, 0.68073513, 0.24847929,
0.06411332, -0.42888773, -0.4308731 , 0.28863559, -0.39317157,
0.6535631 , -1.03377091, 0.82276069, 0.62719534, 0.60430812,
-0.66642475, -0.82981853, -0.23608257, -0.79722868, -0.04271116,
-1.4547114 , -0.36257698, -1.51886097, 0.82684717, -0.52092058,
-0.26407561, -1.26248144, 1.03907498, 1.10227367, -1.44444213,
2.77433472, 1.16802956, -0.40984097, -0.77560109, -0.09912853,
-0.54654941, 0.24287845, -0.84331085, -0.65950241, -0.08166242])
In:
np.random.uniform(-1,2,10) #均勻分布,-1是最低值玛歌,2是最高值
out:
array([ 1.62022332, -0.10385265, 1.7091309 , -0.74307353, 0.82105525,
1.9984005 , 1.2537413 , 0.19649023, 0.27706096, -0.13709349])
In:
a3
np.random.shuffle(a3)
print(a3)
out:
[9 5 0 3 4 1 2 7 6 8]
In:
np.random.choice(10,4) #10表示范圍昧港,4表示個數(shù)
out:
array([6, 2, 3, 0])
In:
a3.mean()
np.average(a3)
out:
4.5
In:
# a3.sum()
np.sum(a3)
out:
45
In:
np.product(a3)
out:
0
In:
np.ptp(a3) #9-0
out:
9
In:
print(a3,a4)
out:
[9 5 0 3 4 1 2 7 6 8] [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
In:
np.minimum(a3,a4)
out:
array([0., 1., 0., 3., 4., 1., 2., 7., 6., 8.])
In:
np.percentile(a3,25) #25代表中位,排序后
out:
2.25
In:
np.percentile(a4,25)
out:
2.25
In:
np.median(a3) #中位數(shù) (4+5)/2,排序后
out:
4.5
In:
a1 = np.array([1,2,'a','hello',[1,2,3],{'one':100,'two':200}])
a1.shape
out:
(6,)
In:
list('abcdef')
out:
['a', 'b', 'c', 'd', 'e', 'f']
In:
a2 = np.array([list(range(6)),list('abcdef'),
[True,False,True,False,True,True]])
In:
a2.shape
out:
(3, 6)
In:
np.arange(5,15)
out:
array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
In:
np.zeros((4,4))
out:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
In:
np.ones((2,3))
out:
array([[1., 1., 1.],
[1., 1., 1.]])
In:
np.eye(3) #生成對角陣
out:
array([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
In:
print(a3)
a3[[3,3,-3,8]]
out:
[0 1 2 3 4 5 6 7 8 9]
array([3, 3, 7, 8])
In:
np.arange(25).reshape(5,5)
out:
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]])
In:
a21 = np.arange(20)
In:
a21.reshape(4,5)
out:
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19]])
In:
np.resize(a21,(5,6))
out:
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 0, 1, 2, 3],
[ 4, 5, 6, 7, 8, 9]])
In:
np.arange(16).reshape(4,4).astype(np.str)
out:
array([['0', '1', '2', '3'],
['4', '5', '6', '7'],
['8', '9', '10', '11'],
['12', '13', '14', '15']], dtype='<U11')
In:
ar6 = np.arange(10).reshape(2,-1)
ar6[ar6>5]
out:
array([6, 7, 8, 9])