參考[Numpy文檔]https://docs.scipy.org/doc/numpy-dev/user/quickstart.html
Numpy的安裝
MacOS
#使用Python3+
pip3 install numpy
#使用Python2+
pip install numpy
Ubuntu
在terminal中運(yùn)行:
sudo apt-get install python-numpy
Numpy的屬性
使用Numpy首先應(yīng)當(dāng)導(dǎo)入Module
import numpy as np
列表轉(zhuǎn)化為矩陣
array = np.array([[1,2,3],[2,3,4]]
print(array)
"""
array([[1, 2, 3],
[2, 3, 4]])
"""
Numpy的重要屬性:
nidm:維度
shape:行數(shù)和列數(shù)
size:元素個(gè)數(shù)
print('number of dim:',array.ndim) # 維度
# number of dim: 2
print('shape :',array.shape) # 行數(shù)和列數(shù)
# shape : (2, 3)
print('size:',array.size) # 元素個(gè)數(shù)
# size: 6
Numpy的創(chuàng)建array
關(guān)鍵字
array:創(chuàng)建數(shù)組
dtype:指定數(shù)據(jù)類型
zeros:創(chuàng)建數(shù)據(jù)全為0
ones:創(chuàng)建數(shù)據(jù)全為1
empty:創(chuàng)建數(shù)據(jù)接近0
arrange:按指定范圍創(chuàng)建數(shù)據(jù)
linspace:創(chuàng)建線段
創(chuàng)建數(shù)組
a = np.array([2,23,4]) #list 1d
print(a)
#[2,23,4]
指定數(shù)據(jù)的type
a = np.array([2,23,4],dtype=np.int)
print(a.dtype)
# int 64
a = np.array([2,23,4],dtype=np.int32)
print(a.dtype)
# int32
a = np.array([2,23,4],dtype=np.float)
print(a.dtype)
# float64
a = np.array([2,23,4],dtype=np.float32)
print(a.dtype)
# float32
創(chuàng)建特定數(shù)據(jù)
注意array與ndarray的區(qū)別磷杏,array一般只用來處理向量,功能也相對(duì)較少脆霎。ndarray可以處理多維矩陣评架。
a = np.array([[2,23,4],[2,32,4]]) # 2d 矩陣 2行3列
print(a)
"""
[[ 2 23 4]
[ 2 32 4]]
"""
a = np.zeros((3,4)) # 數(shù)據(jù)全為0丁眼,3行4列
"""
array([[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.],
[ 0., 0., 0., 0.]])
"""
a = np.ones((3,4),dtype = np.int) # 數(shù)據(jù)為1, 3行4列
"""
array([[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]])
"""
a = np.empty((3,4)) # 數(shù)據(jù)為empty耸携,3行4列
"""
array([[ 0.00000000e+000, 4.94065646e-324, 9.88131292e-324,
1.48219694e-323],
[ 1.97626258e-323, 2.47032823e-323, 2.96439388e-323,
3.45845952e-323],
[ 3.95252517e-323, 4.44659081e-323, 4.94065646e-323,
5.43472210e-323]])
"""
a = np.arange(10,20,2) # 10-19 的數(shù)據(jù)棵癣,2步長
"""
array([10, 12, 14, 16, 18])
"""
a = np.arange(12).reshape((3,4)) # 3行4列,0到11
"""
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
"""
a = np.linspace(1,10,20) # 開始端1夺衍,結(jié)束端10狈谊,且分割成20個(gè)數(shù)據(jù),生成線段
"""
array([ 1. , 1.47368421, 1.94736842, 2.42105263,
2.89473684, 3.36842105, 3.84210526, 4.31578947,
4.78947368, 5.26315789, 5.73684211, 6.21052632,
6.68421053, 7.15789474, 7.63157895, 8.10526316,
8.57894737, 9.05263158, 9.52631579, 10. ])
"""
a = np.linspace(1,10,20).reshape((5,4)) # 更改shape
"""
array([[ 1. , 1.47368421, 1.94736842, 2.42105263],
[ 2.89473684, 3.36842105, 3.84210526, 4.31578947],
[ 4.78947368, 5.26315789, 5.73684211, 6.21052632],
[ 6.68421053, 7.15789474, 7.63157895, 8.10526316],
[ 8.57894737, 9.05263158, 9.52631579, 10. ]])
"""
注意沟沙,這里調(diào)用的許多方法中的參數(shù)都是tuple河劝,其中arange()函數(shù)中的步長可以是float,由于浮點(diǎn)數(shù)的性質(zhì)可能在運(yùn)算前不知道這樣的操作會(huì)產(chǎn)生長度幾何的數(shù)據(jù)矛紫,所以一般使用linspace()做代替赎瞎。
Numpy基礎(chǔ)運(yùn)算
從一個(gè)腳本開始聊Numpy相關(guān)的運(yùn)算:
import numpy as np
a=np.array([10,20,30,40]) # array([10, 20, 30, 40])
b=np.arange(4) # array([0, 1, 2, 3])
Numpy的幾種基本運(yùn)算
矩陣的減法:
c = a - b # array([10, 19, 28, 37])
矩陣加法:
c = a + b
矩陣乘法: (這里的乘法指的是矩陣中的元素對(duì)應(yīng)相乘)
c = a * b
矩陣乘方:
c=b**2 # array([0, 1, 4, 9])
Numpy中調(diào)用一些基本函數(shù)都需要從Numpy的Module中獲得:
c=10*np.sin(a)
# array([-5.44021111, 9.12945251, -9.88031624, 7.4511316 ])
對(duì)多維矩陣而言:
a=np.array([[1,1],[0,1]])
b=np.arange(4).reshape((2,2))
print(a)
# array([[1, 1],
# [0, 1]])
print(b)
# array([[0, 1],
# [2, 3]])
標(biāo)準(zhǔn)的矩陣相乘:
c_dot = np.dot(a,b)
# array([[2, 4],
# [2, 3]])
針對(duì)大小比較而言,我們可以直接使用大小符號(hào)進(jìn)行布爾運(yùn)算颊咬,也可以通過Numpy自帶的Module對(duì)最大值等數(shù)值特征進(jìn)行計(jì)算:
import numpy as np
a=np.random.random((2,4))
print(a)
# array([[ 0.94692159, 0.20821798, 0.35339414, 0.2805278 ],
# [ 0.04836775, 0.04023552, 0.44091941, 0.21665268]])
np.sum(a) # 4.4043622002745959
np.min(a) # 0.23651223533671784
np.max(a) # 0.90438450240606416
print("a =",a)
# a = [[ 0.23651224 0.41900661 0.84869417 0.46456022]
# [ 0.60771087 0.9043845 0.36603285 0.55746074]]
print("sum =",np.sum(a,axis=1))
# sum = [ 1.96877324 2.43558896]
print("min =",np.min(a,axis=0))
# min = [ 0.23651224 0.41900661 0.36603285 0.46456022]
print("max =",np.max(a,axis=1))
# max = [ 0.84869417 0.9043845 ]
Numpy索引
import numpy as np
A = np.arange(2,14).reshape((3,4))
# array([[ 2, 3, 4, 5]
# [ 6, 7, 8, 9]
# [10,11,12,13]])
print(np.argmin(A)) # 0
print(np.argmax(A)) # 11
num中的基本統(tǒng)計(jì)運(yùn)算
求平均:
print(np.mean(A)) # 7.5
print(np.average(A)) # 7.5
print(A.mean())
求中位數(shù):
print(A.median())
求相鄰和:
print(np.cumsum(A))
# [2 5 9 14 20 27 35 44 54 65 77 90]
求相鄰差:
print(np.diff(A))
# [[1 1 1]
# [1 1 1]
# [1 1 1]]
nonzero()函數(shù)(將所有非零元素的行與列坐標(biāo)隔開务甥,重構(gòu)成兩個(gè)分別關(guān)于行和列的矩陣):
print(np.nonzero(A))
# (array([0,0,0,0,1,1,1,1,2,2,2,2]),array([0,1,2,3,0,1,2,3,0,1,2,3]))
排序(每一行從大到小):
import numpy as np
A = np.arange(14,2, -1).reshape((3,4))
# array([[14, 13, 12, 11],
# [10, 9, 8, 7],
# [ 6, 5, 4, 3]])
print(np.sort(A))
# array([[11,12,13,14]
# [ 7, 8, 9,10]
# [ 3, 4, 5, 6]])
矩陣的轉(zhuǎn)置:(這里的轉(zhuǎn)置不適用與向量)
print(np.transpose(A))
print(A.T)
# array([[14,10, 6]
# [13, 9, 5]
# [12, 8, 4]
# [11, 7, 3]])
# array([[14,10, 6]
# [13, 9, 5]
# [12, 8, 4]
# [11, 7, 3]])
有趣的clip()函數(shù):
#clip(Array,Array_min,Array_max)
#Array指的是將要被執(zhí)行用的矩陣贪染,而后面的最小值最大值則用于讓函數(shù)判斷矩陣中元素是否有比最小值小的或者比最大值大的元素缓呛,并將這些指定的元素轉(zhuǎn)換為最小值或者最大值。
print(A)
# array([[14,13,12,11]
# [10, 9, 8, 7]
# [ 6, 5, 4, 3]])
print(np.clip(A,5,9))
# array([[ 9, 9, 9, 9]
# [ 9, 9, 8, 7]
# [ 6, 5, 5, 5]])
Numpy索引
一維索引
與一般的Python list 相同
多維索引
A = np.arange(3,15).reshape((3,4))
"""
array([[ 3, 4, 5, 6]
[ 7, 8, 9, 10]
[11, 12, 13, 14]])
"""
print(A[2])
# [11 12 13 14]
取以上二位矩陣中的元素:
print(A[1][1]) # 8
print(A[1, 1]) # 8
元素的slice:
print(A[1, 1:3]) # [8 9]
迭代:
for row in A: #遍歷每一行
print(row)
"""
[ 3, 4, 5, 6]
[ 7, 8, 9, 10]
[11, 12, 13, 14]
"""
for column in A.T:
print(column)
"""
[ 3, 7, 11]
[ 4, 8, 12]
[ 5, 9, 13]
[ 6, 10, 14]
"""
flatten是一個(gè)展開性質(zhì)的函數(shù)杭隙,將多維的矩陣展開成一行的數(shù)列哟绊。flat是一個(gè)迭代器,本身是object屬性痰憎。
import numpy as np
A = np.arange(3,15).reshape((3,4))
print(A.flatten())
# array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
for item in A.flat:
print(item)
# 3
# 4
……
# 14
Numpy合并
np.vstack():按垂直方向的合并
import numpy as np
A = np.array([1,1,1])
B = np.array([2,2,2])
print(np.vstack((A,B))) # vertical stack
"""
[[1,1,1]
[2,2,2]]
"""
np.hstack():按水平方向的合并
D = np.hstack(A,B)
print(D)
# [1,1,1,2,2,2]
print(A.shape,D.shape)
# (3,) (6,)# [1,1,1,2,2,2]
print(A.shape,D.shape)
# (3,) (6,)
前一節(jié)中說的向量不可以使用 .T 進(jìn)行轉(zhuǎn)置操作票髓,這里給出應(yīng)當(dāng)采用的方法:
print(A[np.newaxis,:])
# [[1 1 1]]
print(A[np.newaxis,:].shape)
# (1,3)
print(A[:,np.newaxis])
"""
[[1]
[1]
[1]]
"""
print(A[:,np.newaxis].shape)
# (3,1)
針對(duì)多個(gè)矩陣和序列的合并方法:
C = np.concatenate((A,B,B,A),axis=0)
print(C)
"""
array([[1],
[1],
[1],
[2],
[2],
[2],
[2],
[2],
[2],
[1],
[1],
[1]])
"""
D = np.concatenate((A,B,B,A),axis=1)
print(D)
"""
array([[1, 2, 2, 1],
[1, 2, 2, 1],
[1, 2, 2, 1]])
"""
Numpy分割
創(chuàng)建數(shù)據(jù):
import numpy as np
A = np.arange(12).reshape((3, 4))
print(A)
"""
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
"""
縱向分割:
print(np.split(A, 2, axis=1)) #只是等分成2份
"""
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
"""
橫向分割:
print(np.split(A,2,axis=0))
# [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
不等量的分割:np.array_split()
print(np.array_split(A,3,axis=1))
"""
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2],
[ 6],
[10]]), array([[ 3],
[ 7],
[11]])]
"""
其他分割:
np.vsplit()
np.hsplit()
print(np.vsplit(A, 3)) #等于 print(np.split(A, 3, axis=0))
# [array([[0, 1, 2, 3]]), array([[4, 5, 6, 7]]), array([[ 8, 9, 10, 11]])]
print(np.hsplit(A, 2)) #等于 print(np.split(A, 2, axis=1))
"""
[array([[0, 1],
[4, 5],
[8, 9]]), array([[ 2, 3],
[ 6, 7],
[10, 11]])]
"""
Numpy copy & deep copy
注意在Numpy中和一般的Python中變量賦值的區(qū)別:
= 的賦值帶有關(guān)聯(lián)性:
import numpy as np
a = np.arange(4)
# array([0, 1, 2, 3])
b = a
c = a
d = b
改變a的第一個(gè)值,b铣耘,c洽沟,d的第一個(gè)值也會(huì)改變:
a[0] = 11
print(a)
# array([11, 1, 2, 3])
#確認(rèn)b,c蜗细,d是否與a相同
b is a # True
c is a # True
d is a # True
d[1:3] = [22, 33] # array([11, 22, 33, 3])
print(a) # array([11, 22, 33, 3])
print(b) # array([11, 22, 33, 3])
print(c) # array([11, 22, 33, 3])
copy()的賦值方法沒有關(guān)聯(lián)性:
b = a.copy() # deep copy
print(b) # array([11, 22, 33, 3])
a[3] = 44
print(a) # array([11, 22, 33, 44])
print(b) # array([11, 22, 33, 3])