1.數組屬性
數組屬性反映了數組本身固有的信息。
屬性名字 | 屬性解釋 |
---|---|
ndarray.shape | 數組維度的元組 |
ndarray.ndim | 數組維數 |
ndarray.size | 數組中的元素數量 |
ndarray.itemsize | 一個數組元素的長度(字節) |
ndarray.dtype | 數組元素的類型 |
2.數組生成
-
生成0和1數組
- np.empty(shape[, dtype, order]) empty_like(a[, dtype, order, subok])
eye(N[, M, k, dtype, order]) - np.identity(n[, dtype])
- np.ones(shape[, dtype, order])
- np.ones_like(a[, dtype, order, subok])
- np.zeros(shape[, dtype, order]) zeros_like(a[, dtype, order, subok])
full(shape, fill_value[, dtype, order]) - np.full_like(a, fill_value[, dtype, order, subok])
- np.empty(shape[, dtype, order]) empty_like(a[, dtype, order, subok])
-
從現有數組生成
- np.array(object[, dtype, copy, order, subok, ndmin])
- 從現有的數組中創建
- np.asarray(a[, dtype, order])
- 相當於建立索引
- np.asanyarray(a[, dtype, order]) ascontiguousarray(a[, dtype])
- np.asmatrix(data[, dtype])
- np.copy(a[, order])
- np.array(object[, dtype, copy, order, subok, ndmin])
-
生成固定範圍的數組
- np.linspace (start, stop, num, endpoint, retstep, dtype)
- 生成等間隔的序列
- start 起始值
- stop 終止值
- num 個數默認50
- endpoint 是否包含stop的值 默認爲True
- retstep True 返回樣例
- dtype 數據類型
- np.arange(start,stop, step, dtype)
- np.logspace(start,stop, num, endpoint, base, dtype)
- np.linspace (start, stop, num, endpoint, retstep, dtype)
-
生成隨機數組
-
均勻分佈
-
np.random.rand(d0, d1, …, dn)
- [0, 1]之間
-
np.random.uniform(low=0.0, high=1.0, size=None)
- [low, high)之間 小數
-
np.random.randint(low, high=None, size=None, dtype=‘l’)
- 整數
-
正態分佈
-
np.random.randn(d0, d1, …, dn)
- 標準正態分佈
-
np.random.normal(loc=0.0, scale=1.0, size=None)
- loc 均值 scale 標準差
-
np.random.standard_normal(size=None)
- 指定形狀的標準正態分佈
-
3.形狀改變
- ndarray.reshape() 返回轉換後的數組
- ndarray.resize() 替換原來的數組
- ndarray.T 轉置 行列互換
4.類型修改
- ndarray.astype()
- ndarray.tostring()
- ndarray.tobytes()
5.數組去重
- np.unique()
6.邏輯運算
import numpy as np
stock_change = np.random.normal(0, 1, (8, 10))
stock_change = stock_change[0:5, 0:5]
# 值大於0.5 設置爲1
stock_change[stock_change > 0.5] = 1
-
np.all() 所有
-
np.any() 任意
-
np.where(條件, 爲真處理, 爲假處理) 三元運算符
- np.where(stock_change > 0.5, 1, 0) 值大於0.5 的設爲1, 否則爲0
- 復合邏輯
- 多個條件 and : np.logical_and()
- 多個條件 or : np.logical_or()
7.統計指標
- ndarray.min() 最小值
- ndarray.argmin() 最小值的位置
- ndarray.max() 最大值
- ndarray.argmax() 最大值的位置
- ndarray.mean() 平均值
- ndarray.std() 標準差
- ndarray.var() 方差
- np.median(ndarray) 中位數 np纔有這個方法
- 多維數組 通過axis 指定基於某個緯度 計算 a.min(axis=1)
8. 廣播
- 兩個array 的形狀 倒過來 從尾部開始比較, 對應數字相等 或其中任意一個爲1 纔可以廣播
- (2, 5) 和 (5,)
- (2, 3, 2, 4) 和 (1, 2, 1)
9. 矩陣運算
-
矩陣必須是2維的, 相乘必須滿足形狀 (m,n) * (n, l) = (m, l)
-
np.mat() 將數組轉換爲矩陣, 矩陣必須是2維的, 轉成了matrix類型
-
矩陣相乘 必須要注意緯度, 可以利用reshape()轉換
- matrix類型 直接用 * 相乘
- array類型 np.dot() 和 np.matmul()
10.合併與分割
-
np.concatenate() 通過axis=0 / 1 控制 水平/垂直合併
-
np.hstack() 水平合併
-
np.vstack() 垂直合併
-
np.split()
- np.split(x, 3) 平均切分3份
- 指定切分點 np.split(x, [2, 7]) 索引爲2 和7 作爲切分點