numpy
文章目錄
Numpy
-
import numpy as np # 創建矩陣 np.mat(np.random.randint(100,200,50).reshape(10,5))
-
np.mat( np.arange(12).reshape(3,4) ) # 數組轉矩陣
矩陣
- 矩陣:二維數組
- 特例
- 向量:1xn或nx1的矩陣
- 標量:1x1的矩陣
- 特殊矩陣
- 全0全1矩陣
- 單位矩陣
- 運算
- 相加、減的兩個矩陣
- 必須有相同的行和列
- 行和列對應元素相加減
- 矩陣的乘法
- mxp的矩陣 * pxn的矩陣 = mxn的矩陣
- 矩陣*單位矩陣
- 相加、減的兩個矩陣
- 特例
數組
- 運算
- 加法
*
- 加法
ndarray數組的創建
創建 | 含義 | |
---|---|---|
np.array(list/tuple,dtype=np.float32) | 列表、元組類型創建 | np.array([[1,2],[3,4],(5,6)]) |
np.arange(n) | 元素從0到n-1 | np.arange(10) |
np.ones(shape) | 全1數組 shape是元組類型 |
np.ones((3,4)) |
np.ones((2,3,4)) | 最外層有2個元素 每個元素有3個維度 每個維度下有4個元素 |
|
np.zeros(shape) | 全0數組 | np.zeros((3,4),dtype=np.int32) |
np.full(shape,val) | 生成shape數組 每個元素值爲val |
np.full((2,2),‘a’) |
np.eye(n) | n*n單位矩陣 對角線爲1 其餘爲0 |
np.eye(5) |
-
函數 說明 np.ones_like(a) 根據數組a的形狀生成一個全1數組 np.zeros_like(a) 根據數組a的形狀生成一個全1數組 np.full_like(a,val) 根據數組a的形狀生成一個數組,每個元素值爲val -
函數 說明 np.linspace() 根據起止數據等間距地填充數據,形成數組 np.concatenate() 將2個或多個數組合併成一個新的數組 -
a = np.linspace(1,10,4) # [1,10] b = np.linspace(1,10,4,endpoint=False) # [1,10) np.concatenate((a,b))
-
ndarray數組的維度變換
方法 | 說明 |
---|---|
.reshape(shape) | 不改變數組元素,返回一個shape形狀的數組,原數組不變 |
.resize(shape) | 與.reshape()功能一致,但修改原數組 |
.swapaxes(ax1,ax2) | 將數組n個維度中兩個維度進行調換 |
.flatten() | 將數組進行降維,返回摺疊後的以爲數組,原數組不變 |
屬性
-
軸,axis,保存數據的維度
-
秩,rank,軸的數量
a = np.array([[],[]]) a.ndim # 秩、軸的數量或維度的數量
-
屬性 說明 .ndim 秩,軸的數量或維度的數量 .shape 對於矩陣,n行m列 .size ndarray對象元素的個數 .dtype ndarray對象的元素類型 .itemsize ndarray對象中每個元素的大小,字節爲單位
ndarray的元素類型
數據類型 | 說明 |
---|---|
bool | 布爾類型 |
intc | 與C語言的int類型一致,int32或int64 |
intp | 用於索引的整數,int32或int64 |
int8 | 字節長度的整數,取值:[-128,127] |
int16 | 16位長度的整數,取值:[-32768,32767] |
int32 | 32位長度的整數,取值:[-231, 231-1] |
int64 | 64位長度的整數,取值:[-263, 263-1] |
uint8 | 8位無符號整數,取值:[0,255] |
uint16 | 16位無符號整數,取值:[0,65535] |
uint32 | 32位無符號整數,取值:[0,232-1] |
uint64 | 64位無符號整數,取值:[0,264-1] |
float16 | 16位版精度浮點數:1位符號位,5位指數,10位位數 |
float32 | 32位版精度浮點數:1位符號位,8位指數,23位位數 |
float64 | 64位版精度浮點數:1位符號位,11位指數,52位位數 |
complex64 | 複數類型,實部和虛部都是32位浮點數 |
complex128 | 複數類型,實部和虛部都是64位浮點數 |
- 實部(.real)+j虛部(.imag)
- 非同質的ndarray元素爲對象類型(大規模數據處理,儘量避免使用非同質對象)
- 非同質對象:元素1和元素2的夠成數量不一
- 元素1由3個元素構成,元素2由5個元素構成
- 元素1和元素2組成的ndarray對象爲非同質對象
- 非同質對象:元素1和元素2的夠成數量不一
ndarra數組的類型變換
new_a = a.astype(new_type)
- astype()方法一定會創建新的數組(原始數據的一個拷貝),即使兩個類型一致。
ndarray數組向列表的轉換
-
ls = a.tolist()
-
a = np.full((2,3,5),25,dtype=np.int32) a.tolist()
運算
-
數組與標量之間的運算
-
作用於數組的每一個元素
-
a = np.arange(4).reshape(2,2) b = np.arange(4,0,-1).reshape(2,2) a * b # 按索引位置,對應相乘 a.dot(b) # 矩陣乘法 np.dot(a,b) # 矩陣乘法
-
Numpy一元函數unary ufunc
一元ufunc | 說明 |
---|---|
np.abs()、np.fabs() | 計算整數、浮點數或複數的絕對值。 對於非複數值,可以使用更快的fabs |
np.sqrt() | 計算各元素的平方根:arr ** 0.5 |
np.square() | 計算各元素的平方:arr ** 2 |
np.exp() | 計算各元素的指數ex |
np.log()\np.log10\np.log2\np.log1p | 分別:自然對數(e爲底數),底數爲10的log,底數爲2的log,log(1+x) |
np.sign() | 計算各元素的正負號:1(正數),0(零),-1(負數) |
np.ceil() | 向上取整 |
np.floor() | 向下取整 |
np.rint() | 四捨五入取整 |
np.modf() | 小數部分和正數部分以兩個獨立數組返回arr1,arr2 = np.modf(arr3) |
np.isnan() | 返回一個布爾型數組:“哪些值是NaN" |
np.isfinite()\np.isinf() | 返回布爾型數組:哪些元素是有窮的,哪些元素是無窮的 |
np.cos()\np.sin()\np.tan() | 普通型三角函數 |
np.cosh()\np.sinh()\np.tanh() | 雙曲型三角函數 |
np.arccos()\np.arcsin()\np.arctan() | 反三角函數 |
np.arccosh()\np.arcsinh()\np.arctanh() | 反三角函數 |
np.logical_not() | 計算各元素not x的真值 相當於-arr |
Numpy二元函數 binary ufunc
二元ufunc | 說明 |
---|---|
np.add(arr1,arr2) | 將數組對應元素相加 |
np.subtract() | 從第一個數組中,減去第二個數組中的元素 |
np.multiply() | 數組元素相乘 |
np.divide() | 除法 |
np.floor_divide() | 向下圓整除法(丟棄餘數) |
np.power() | 對第一個數組中的元素A,根據第二個數組中相應元素B,計算AB |
np.maximum() | 元素級的最大值計算 |
np.fmax() | 忽略NaN的,元素級的最大值計算 |
np.minimum() | 元素級的最小值計算 |
np.fmin() | 忽略NaN的,元素級的最小值計算 |
np.mod() | 元素級的求模計算(除法的餘數) |
np.copysign() | 將第二個數組中的值的符號賦值給第一個數組中的值 |
np.greater() | 執行元素級的比較>,產生布爾型數組 |
np.greater_equal() | 執行元素級的比較>=,產生布爾型數組 |
np.less() | 執行元素級的比較<,產生布爾型數組 |
np.less_equal() | 執行元素級的比較<=,產生布爾型數組 |
np.equal() | 執行元素級的比較==,產生布爾型數組 |
np.not_equal() | 執行元素級的比較!=,產生布爾型數組 |
np.logical_and() | 執行元素級的真值邏輯元素:& ,且 |
np.logical_or() | 執行元素級的真值邏輯元素:|,或 |
np.logical_xor | 執行元素級的真值邏輯元素:^,異或 |
矢量化三元表達式 np.where(arr1,第二個參數,第三個參數)
-
第二個和第三個參數不必是數組,可以是標量值
-
相當於
x if condition else y
的矢量化版本 -
np.where(arr1>0,1,-1)# 元素>0的返回1,否則返回-1
-
類似於MySQL的控制流函數
-
select education,salary,case education when '大專' then 1 when '本科' then 2 when '碩士' then 3 when '博士' then 4 else 0 end as tmp from demp_table;
-
相當於MySQL的三元表達式
-
select education,if(salary > 9,'優先','等待') as tmp from demp_talbe;
-
python的三元表達式結果1 if 表達式 else 結果2
-
a = 10 b = 20 r = a if a>b else b
-
python列表推倒時
-
list1 = [i*i for i in range(2,11,2)]#生成1~10之間的所有偶數
隨機數組
函數 | 說明 |
---|---|
np.random.rand() | 均勻分佈,[0,1),浮點數 |
np.random.randn(3,4,5) | 標準正態分佈 均值:1 標準差0 |
np.random.randint(low,[high,shape]) | 範圍[low,high),隨機整數 |
np.random.seed() | 隨機數種子 |
函數 | 說明 |
---|---|
np.random.shuffle(a) | 根據數組a的第1軸(最外層維度)進行隨排列,改變數組a |
np.random.permutation(a) | 同上,不改變數組a |
np.random.choice(a[,size,replace,p]) | 從一維數組a中以概率p抽取元素 形成size形狀新數組 replace表示是否可以重用元素 |
-
b = np.random.randint(100,200,(8,)) np.random.choice(b,(3,2)) np.random.choice(b,(3,2),replace=False) # 之前被選取元素不再被選取 np.random.choice(b,(3,2),p = b/np.sum(b))
函數 | 說明 |
---|---|
np.random.uniform(low,high,size) | 均勻分佈, [low,high) size形狀 |
np.random.normal(loc,scale,size) | 正態分佈, loc均值, scale標準差 |
np.random.poisson(lam,size) | 泊松分佈 lam隨機事件發生概率 size形狀 |
統計函數
- axis=None 是統計函數的標配參數
- axis爲整數、元組
函數 | 說明 |
---|---|
np.sum(a,axis=None) a.sum(axis=None) |
|
np.mean(a,axis=None) a.mean(axis=None) |
|
np.average(a,axis=None,weights=None) | 加權平均值 weights輸入每個元素加權值 |
np.std(a,axis=None) a.std(axis=None) |
標準差 |
np.var(a,axis=None) a.var(axis=None) |
方差 |
函數 | 說明 |
---|---|
np.min(a) | |
np.max(a) | |
np.argmin(a) a.argmin() |
計算數組a中元素最小值的降一維後下標 |
np.argmax(a) a.argmax() |
扁平化後的下標 |
np.unravel_index | 根據shape將一維下標index轉換成多維下標 |
np.ptp(a) | 最大值 - 最小值 |
np.median(a) | 中位數(中值) |
-
扁平化後的下標–重塑成多維下標
np.unravel_index(np.argmax(b),b.shape)
梯度函數 | 說明 |
---|---|
np.gradient(f) | 計算數組f中元素的梯度, 當f爲多維時,返回每個維度梯度 |
- 梯度:連續值之間的變化率,即斜率
- XY座標軸連續是哪個X座標對應的Y軸值:a,b,c,其中,b的梯度是:(c-a)/2
a.cumsum(0) | 列累加 |
---|---|
a.cumprod(1) | 行累加 |
IO
Numpy便捷文件存取
-
np.save(fname, array) # 擴展名爲.npy np.savez(fname, array) # 壓縮擴展名爲.npz
-
np.load(fname) # 以.npy爲擴展名,壓縮擴展名爲.npz
By 儒冠多誤身 2019/04/21