Numpy學習筆記
ndarray多維數組
創(chuàng)建
import numpy as np
np.array([1,2,3,4])
np.array([1,2,3,4,],[5,6,7,8])
np.zeros(8)
np.zeros(3,4)
np.ones(4)
np.one_like([1,2,3,4])
np.empty((2,2,2))
np.arange(10)
數組創(chuàng)建函數
- arange
- ones/ones_like
- zeros/zeros_like
- empty/empty_like
- eye/identity
屬性
- ndim: 軸的個數
- shape: 數組的維度
- size: 元素總個數
- dtype: 數據類型
- itemsize: 每個元素的字節(jié)大小
數據類型
- float
- int
- complex
- bool
- string_
- object
類型轉換
attr1.astype(np.float64) # np.float64和'float64'都可以
attr1.astype('string_')
attr1.astype('int32')
數組變換
- reshage: 變換
- flattern: 扁平
- ravel: 散開
arr1 = np.arrary(9)
arr.reshape((3,3))
arr.reshape((3, -1)) # -1根據數據數據本身/3決定
3種變換(數據重塑)都不會修改原數組
- concatenate: 合并
- split: 拆分
arr1 = np.arrage(12).reshape(3, 4)
arr2 = np.arrange(12,24).reshape(3,4)
np.concatenate([arr1, arr2], axis=0) # 相當于np.vstack([arr1, arr2])
np.concatenate([arr1, arr2], axis=1) # 相當于np.hstack([arr1, arr2])
np.split(arr1, [2, 4])
- transpose: 數組轉制(只支持2維)
- swapaxes: 軸對換(支持多維)
arr1 = np.arange(12).reshape(3,4)
arr1.transpose((1,0)) # 相當于 arr1.T
arr2 = np.arrage(16).reshape(2,2,4)
arr2.swapaxes(1,2) # 交換y,z軸
隨機函數(random)
- rand: 均勻分布的樣品值
- randint: 隨機整數
- randn: 平均數為0, 標準差為1的正態(tài)分布隨機數
- normal: 指定平均數和標準差的正態(tài)分布數組
- seed: 隨機種子
- permutation: 隨機排序, 不改變原數組
- shuffle: 隨機排序,改變原數組
- uniform(low, high, size): 均勻分布的數組
- poisson(lam, size): 泊松分布數組
arr1 = np.random.randint(100, 200, size=(5,4))
np.random.randn(2,3,5)
np.random.normal(4,5,size=(3,5))
np.random.permutation(arr1)
np.random.shuffle(arr1)
數組的索引和切片
- 索引支持多維索引arr1[2,3] 或arr1[2][3]
- 索引值為原數組的視圖, 修改arr1[2,3]會修改原數組(如并不想修改需使用arr1[2,3].copy())
- 切片支持多維切片arr1[2:, :-1]
- 布爾型索引 datas[fruits==0] = 1 # 篩選賦值
- 花式索引: arr[np.ix_([3,2],[2,1]) # arr[[3,2]][:,[2,1]]
數組運算
標量運算
arr1 = np.array([1, 2, 3])
arr1 * 10
arr1 * arr1
arr1 - arr1
通用函數
- abs: 絕對值
- square: 平方
- add: 兩個數組相加
- minimum: 計算最小值
- modf: 分割整數部分和小數部分
可以指定axis軸
條件邏輯運算
- np.where(cond, arr1, arr2) # 類似3元表達式
統(tǒng)計運算
- sum: 求和
- mean: 求算術平均數
- std/var: 求標準差/方差
- min/max: 最小數/最大數
- argmin/argmax: 最小數/最大數索引
- cumsum: 所有元素的累加和
- cumprod 所有元的累計積
- all/any: 布爾類型運算
集合運算
- np.unique: 找出所有唯一值,并排序
- np.inld: 是否包含指定的值
- np.intersect1d: 公共元素
- np.union1d: 并集
- np.setdiff1d: 差集
- setxor1d: 交集取反
線性代數
- np.dot: 點積
- from numpy.linalg import det ...
數組存取
- np.loadtxt: 讀取
arr1 = np.loadtxt('1.csv', delimiter=',')