NumPy基礎
●NumPy ( Numerical Python , NumPy )庫長期以來一直是Python科學計算的基石,它提供了數值數據的大多數科學應用所需的數據結構和算
法,還有包括以下:
●快速高效的多維數組的對象(numpy.ndarray)
●用於對數組執行元素級計算以及直接對數組執行數學運算的函數
●用於讀寫硬盤上基於數組的數據集的工具
●線性代數運算、傅里葉變換以及隨機數生成
●用於集成由C、C++、Fortran等語言編寫的代碼的工具
●許多數值計算要麼直接使用NumPy的數組作爲其主要數據類型,要麼兼容NumPy的數據類型
●NumPy數組在存儲和處理數值數據時要比內置的Python數據結構高效得多
●NumPy在數據分析中的重要用途之- 是作爲算法和工具庫之間的傳遞容器
NumPy核心數據類型
●NumPy提供了一個N維數組類型ndarray ( numpy.ndarray) , 它描述了相同類型的元素的集合
●ndarray與原生Python列表的區別:
●ndarray數據與數據的地址都是連續的,而Python列表存儲的是引用地址
●ndarray中的所有元素的類型都是相同的,而Python列表中的元素類型是任意的
●ndarray內置了並行運算功能,當系統有多個核心時, NumPy會自動做並行計算
numpy函數簡單應用
import numpy as np
a = np.arange(10)
print(a)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(a.dtype)
dtype('int64')
print(a.shape)
(10,)
# 用linspace函數創建一個初始值爲1 ,終止值爲19 ,元素個數爲10個的等差數列向量
b = np.linspace(1,19,10)
b
array([ 1., 3., 5., 7., 9., 11., 13., 15., 17., 19.])
# endpoint參數指定是否包含終止值
np.linspace(1,19,10,endpoint=False)
array([ 1. , 2.8, 4.6, 6.4, 8.2, 10. , 11.8, 13.6, 15.4, 17.2])
# 用logspace函數創建一個等比數列向量,基數可以通過base參數指定,默認值爲10
from math import e# 引入自然數e
np.logspace(1,20,10,endpoint=False,base=e)
array([2.71828183e+00, 1.81741454e+01, 1.21510418e+02, 8.12405825e+02,
5.43165959e+03, 3.63155027e+04, 2.42801617e+05, 1.62334599e+06,
1.08535199e+07, 7.25654884e+07])
# 用zeros函數創建一個元素全部爲0的整數型向量
np.zeros(10,np.int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
# 創建一個隨機數向量, randn是numpy.random中生成正態分佈隨機數據的函數
np.random.randn(10)
array([ 0.04384946, -1.97646467, 0.56858477, -0.1958997 , -1.43684069,
-1.09261095, 0.17620979, -0.93042159, -0.41511684, -1.22303696])
# shape屬性表示數組的形狀, ndim屬性表示數組的維數。
c = np.array([np.arange(3),np.arange(3)])
print(c)
print(c.shape)
print(c.ndim)
[[0 1 2]
[0 1 2]]
(2, 3)
2
# 創建單位矩陣
np.identity(9).astype(np.int8)
array([[1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=int8)
c.tolist()
[[0, 1, 2], [0, 1, 2]]
# 查看完整的ndarray數據類型
print(set(np.typeDict.values()))
{<class 'numpy.complex256'>, <class 'numpy.float128'>, <class 'numpy.uint64'>, <class 'numpy.int64'>, <class 'numpy.str_'>, <class 'numpy.complex128'>, <class 'numpy.float64'>, <class 'numpy.uint32'>, <class 'numpy.int32'>, <class 'numpy.bytes_'>, <class 'numpy.complex64'>, <class 'numpy.float32'>, <class 'numpy.uint16'>, <class 'numpy.int16'>, <class 'numpy.bool_'>, <class 'numpy.timedelta64'>, <class 'numpy.float16'>, <class 'numpy.uint8'>, <class 'numpy.int8'>, <class 'numpy.object_'>, <class 'numpy.datetime64'>, <class 'numpy.uint64'>, <class 'numpy.int64'>, <class 'numpy.void'>}
# 結構數組
# 個購物清單,包含的字段主要有:商品名稱、購買地點、價格、數量,可以事先使用dtype函數自定義這些字段的類型:
goodslist = np.dtype([('name',np.str_,50),('location',np.str_,30),('price',np.float16),('number',np.int32)])
goodslist
dtype([('name', '<U50'), ('location', '<U30'), ('price', '<f2'), ('number', '<i4')])
goods = np.array([('Gree Airconditioner','JD.com',6245,1),('Sony Blueray Player','Amonzon.com',3210,2),('Apple Macbook Pro 13','Tmall.com',12388,5),('iPhoneSE','JD.com',4588,2)],dtype=goodslist)
goods
array([('Gree Airconditioner', 'JD.com', 6244., 1),
('Sony Blueray Player', 'Amonzon.com', 3210., 2),
('Apple Macbook Pro 13', 'Tmall.com', 12380., 5),
('iPhoneSE', 'JD.com', 4588., 2)],
dtype=[('name', '<U50'), ('location', '<U30'), ('price', '<f2'), ('number', '<i4')])
goodsdict = np.dtype({'names':['name','location','price','number'],'formats':['U50','U30','f','i']})
goods_new = np.array([('Gree Airconditioner','JD.com',6245,1),('Sony Blueray Player','Amonzon.com',3210,2),('Apple Macbook Pro 13','Tmall.com',12388,5),('iPhoneSE','JD.com',4588,2)],dtype=goodsdict)
goods_new
array([('Gree Airconditioner', 'JD.com', 6245., 1),
('Sony Blueray Player', 'Amonzon.com', 3210., 2),
('Apple Macbook Pro 13', 'Tmall.com', 12388., 5),
('iPhoneSE', 'JD.com', 4588., 2)],
dtype=[('name', '<U50'), ('location', '<U30'), ('price', '<f4'), ('number', '<i4')])
# 多維數組
# shape直接修改內存地址中數組的形狀而reshape不會修改,即shape會修改原始數組, reshape不會修改。
d = np.arange(24).reshape(2,3,4)
d
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]]])
d[1,1,2]
18
d[0,...]# d[0,;,;]
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
d[d>=15]
array([15, 16, 17, 18, 19, 20, 21, 22, 23])
# ndarray對象的latten方法與ravel函數功能相同,但執行flatten函數後,會分配內存保存結果; ravel函數只是返回數組的一個視圖。
# 將爲一維數組
print(d.ravel())
print(c.flatten())
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
[0 1 2 0 1 2]
# 轉置函數a.T np.transpose(a)
# 水平組合即把所有參加組合的數組拼接起來,各數組行數應該相等.函數hstack和concatenate的效果相同,注意垂直組合時concatenate函數中參數axis=0
# 絕對值
m = np.array([1,-2,3,-6,-9,10])
np.abs(m)
array([ 1, 2, 3, 6, 9, 10])
# 平方
np.square(m)
array([ 1, 4, 9, 36, 81, 100])
# numpy中對數組的操作函數
# 平方根sqrt() 以e爲底的指數exp() 以e爲底的對數log(),以2爲底的對數log2(),等等
# 返回各元素的符號sign() 對數組排序sort(),默認升序,對多維數組可在不同軸上排序,對橫軸:參數axis=1
# 去除重複元素unique() 向上取整ceil() 向下取整floor() 四捨五入rint() 小數部分和整數部分分離modf()
# 三角函數sin() cos() tan() 求和sum() 求平均數mean() 求標準差std() 求方差var() 最小值min() 最大值max()
# 最小元素索引argmin() 最大元素索引argmax()
# 計算累計和cumsum()
np.cumsum(m)
array([ 1, -1, 2, -4, -13, -3])
# 計算累計積cumprod()
np.cumprod(m)
array([ 1, -2, -6, 36, -324, -3240])
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
a
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
# 矩陣操作
# 返回矩陣的對角線元素
np.diag(a)
array([1, 5, 9])
# 若爲一維數組,則返回對角矩陣
m = np.array([1,3])
np.diag(m)
array([[1, 0],
[0, 3]])
# 計算對角線元素之和trace() 計算矩陣的行列式(線性代數知識:主對角線之和-次對角線之和)np.linalg.det()
# 矩陣的逆np.linalg.inv() 矩陣點乘np.dot(a,b)
# np.random庫產生隨機數
np.random.rand(2,3) # 產生0,1之間的服從均勻分佈的隨機數
array([[0.85317681, 0.4408503 , 0.41369915],
[0.02701161, 0.29895793, 0.14457146]])
np.random.randint(0,20,size=10) # 給定上下限和數據個數,產生隨機整數
array([13, 17, 17, 0, 5, 3, 17, 5, 10, 19])
np.random.binomial(10,0.5)# 產生滿足二項分佈的隨機數
7