一匆赃、簡介:NumPy(Numerical Python) 是 Python 語言的一個擴展程序庫舶斧,支持大量的維度數(shù)組與矩陣運算尿赚,此外也針對數(shù)組運算提供大量的數(shù)學函數(shù)庫添忘。其實主要用于數(shù)組或矩陣計算
二咕缎、? NumPy Ndarray 對象
ndarray里可以存儲同類型的多維數(shù)組;
創(chuàng)建一個ndarray ,只需要調(diào)用numpy庫中的array函數(shù)即可赏胚;
numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)? object表示數(shù)組或者數(shù)列屋讶,dtype表示數(shù)組元素類型又固,copy表示對象是否需要復制,order表示數(shù)組樣式煤率,C表示行仰冠,F(xiàn)表示列,A表示任意蝶糯。ndmin表示最小維度
代碼:
import numpyas np
#一維數(shù)組
a=np.array([1,2,3])
#二維數(shù)組
b=np.array([[1,2],[3,4]])
#最小維度
c=np.array([[1,2,3],[1,2,4]],ndmin=0)
#dtype類型為復數(shù)的
d=np.array([1,2,3],dtype=complex)
print(a,b,c,d)
三洋只、數(shù)組類型的函數(shù)為dtype()?即numpy.dtype(object, align, copy),其中 numpy.dtype(object, align, copy)昼捍, align - 如果為 true识虚,填充字段使其類似 C 的結構體, copy - 復制 dtype 對象 妒茬,如果為 false舷礼,則是對內(nèi)置數(shù)據(jù)類型對象的引用
代碼
import numpy as np
e= np.dtype(np.int32)
f=np.dtype('i4')
g=np.dtype([('age',np.int8)])
print(e,f,g)
四、NumPy 數(shù)組屬性:
數(shù)組中比較重要 ndarray 對象屬性有:?.ndim表示維度數(shù)量;? .shape表示數(shù)組維度;???對于矩陣郊闯,n 行 m 列; .size?表示數(shù)組元素的總個數(shù)妻献,相當于 .shape 中 n*m 的值;?? .dtype表示數(shù)組類型, 注意這些都是屬性团赁,不是函數(shù)育拨,不需要加()
代碼
import numpy as np
a = np.array([[1,2,3],[4,5,6]])??
print (a.shape)
輸出:(2, 3)
import numpyas np
a = np.array([[1, 2, 3], [4, 5, 6]])
b = a.reshape(3, 2)
print(b)
輸出:
[[1, 2]
[3, 4]
[5, 6]]
五、NumPy 創(chuàng)建數(shù)組
.empty()? ?空數(shù)組 numpy.empty(shape, dtype = float, order = 'C')
.zeros()? ?0矩陣
.ones()? ?1矩陣
代碼
import numpy as np
?x = np.empty([3,2], dtype = int)?
print (x)
輸出[[ 6917529027641081856 5764616291768666155]
?[ 6917529027641081859 -5764598754299804209]?
[ 4497473538 844429428932120]]? ?隨機生成欢摄,沒有初始化
import numpy as np?
?# 自定義類型
z = np.zeros((2,2), dtype = [('x', 'i4'), ('y', 'i4')])
?print(z)
輸出:
[[(0, 0) (0, 0)]
?[(0, 0) (0, 0)]]?
x = np.ones([2,2], dtype = int)
print(x)
輸出:
[[1 1]
?[1 1]]
六熬丧、NumPy 從數(shù)值范圍創(chuàng)建數(shù)組
?arange 函數(shù)創(chuàng)建數(shù)值范圍? numpy.arange(start, stop, step, dtype)??
linspace函數(shù)用于創(chuàng)建一個一維數(shù)組,數(shù)組是一個等差數(shù)列構成的
numpy.logspace 函數(shù)用于創(chuàng)建一個于等比數(shù)列怀挠。 np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)? num是步長析蝴,base是 對數(shù) log 的底數(shù)
import numpyas np
a=np.arange(10,20,3)
print(a)
輸出:[10 13 16 19]
a = np.linspace(1,10,10)
print(a)
輸出:[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] #等差數(shù)列
a = np.logspace(1.0, 2.0, num = 10)? ?#num底數(shù)是10?
print(a)
輸出:[ 10. 12.91549665 16.68100537 21.5443469 27.82559402
? 35.93813664? 46.41588834? ? 59.94842503? ? ? 77.42636827? ? 100.? ? ]
總結:
函數(shù):array() 數(shù)組;dtype()類型;empty()空數(shù)組绿淋;zeros();ones();arange()表示范圍闷畸;
linspace()表示函數(shù)用于創(chuàng)建一個一維數(shù)組,數(shù)組是一個等差數(shù)列構成的
logspace()函數(shù)用于創(chuàng)建一個于等比數(shù)列
transpose()函數(shù)用于對換數(shù)組的維度
屬性:.ndim表示維度數(shù)量;?.shape表示數(shù)組維度;???對于矩陣吞滞,n 行 m 列; .size?表示數(shù)組元素的總個數(shù)佑菩,相當于 .shape 中 n*m 的值;???.dtype表示數(shù)組類型 ; .flat 數(shù)組元素迭代器