可以用list创建
.dtype 查看元素类型
np.zeros(n)
np.zeros(shape=n, dtype=int)
np.zeros((x,y))
np.ones(n)
np.full(shape, fill_value)
np.arange(start, end, step=1)
【注】step可以传入浮点数
np.linspace(start, end, num)
start中截取num个点,start和end包括在内
np.random.randint(0, 10) #生成一个随机数
np.random.randint(0, 10, size) #生成一个随机序列,len=10
np.random.seed(n)
每次生成同样的随机数
np.random.random([size])
np.random.normal()
np.random.normal(E=0,D=1)
np.random.normal(E=0,D=1,size)
【注】size参数是一个元组
方法/模块+?
:np.random.normal?
help(方法)
: 在jupyter内部显示help(np.random.normal)
.ndim
:维度
.shape
:形状
.size
:元素个数
x[0][0]
不建议
x[(0, 0)]
, 简写为:x[0, 0]
[a:b]
、[:b]
、[a:]
[::2]
:头到尾,步长2
X[:2, :3]
:两个维度取切片,前2行,前3列
【注】X[:3][:2]
:先解析X[:3]取前3行,在解析[:3]:在前3行中取前2行
X[:2, ::2]
:前2行,每行间隔2取
X[::-1, ::-1]
:整体反转
X[0, :]
:取第一行
X[:, 0]
:取第一列
list取切片,创建新的list副本,而numpy中赋值只是引用:
subx = X[:2, :3]
用.copy()产生副本
x.shape
new_x = x.reshape(x, y) # 参数是元组
# 返回新的矩阵,但不改变x
x.reshape(10, -1) # 10行,每行自动填充,必须可以整除
np.concatenate([x, y])
np.concatenate([x, y], axis=1) # 默认是0:第一个维度,即沿着行方向拼接
【注】只能处理维数一样的情况:
[[1, 2, 3], [4, 5, 6]] 和 [1, 2, 3]
可以通过reshape解决
np.vstack([A, x]) # 垂直方向堆叠
np.hstack([A, x]) # 水平方向
np.split(l, [x, y]) # x, y 是分割点:切成3段
np.split(l, [x]) # 切成2段
二维矩阵:np.split(A, [x]) # 按行分割,默认axis=0,基于第一个维度
np.split(A, [x], axis=1)
np.vsplit(A. [x]) # 行(垂直)分割
np.hsplit(A. [x]) # 列(水平)分割
x, y = np.hsplit(data, [-1])
y[:, 0] 得到向量
numpy中支持: + - * / …等运算且做了优化(远优于list)
+ - * /
:对应元素间进行运算
A.dot(B)
:矩阵点乘
A.T
:矩阵转置
v + A
:没意义,v和A每一行相加
+
: 低纬相对于高纬运算
np.tile(v, (2, 1))
#堆叠:行上堆叠2次,列上堆叠1次
【注】.dot(v)
自动转换行列向量
invA = np.linalg.inv(A)
pinvx = np.linalg.pinv(x)
pinvx.dot(x)
np.sum(L)、np.min(L)、np.max(L)
也可以: L.min()
计算行和:
np.sum(X, axis=0) # 沿着列(第0个维度)运算 -> 每行的 / 压缩掉第0个维度
乘积:np.prod(X)
均值:np.mean(X)
中位数:np.median(X)
位次:
np.percentile(bit_array, q=50) # 求第50%位的数 = 中位数
通常:for percent in [0, 25, 50, 75, 100] 来观察数据
方差:np.var(big_array)
标准差:np.std(big_array)
【注】axis:维度参数(along with)
返回索引,而不是值:
np.argmin(x)
np.argmax(x)
np.sort(x)
np.sort(x, axis=1)
x.sort() # 默认按行排序
x.sort(axis=1) # 按列排序
np.argsort(x) # 索引排序,范围递增序列对应的索引
np.partition(x. pivot)
np.argpartition(x, pivot)
ind = [3, 5, 8]
x[ind] # 返回3,5,8组成的子向量
ind = np.array([[0, 2],
[1, 3]]) # 全是index
x[ind]
row = np.array([0, 1, 2])
col = np.array([1, 2, 3])
x[row, col]
# 返回array(x[0, 1], x[1, 2], x[2, 3])
x = np.arange(4)
col = [True, False, True, True]
x[col]
x < 3
# 返回布尔数组/矩阵
统计:
np.sum(x < 3)
np.count_nonzero(x < 3)
np.any(x == 0) # 是否有非零元素,有任意满足条件的都返回True
np.all(x >= 0) # 所有元素都非负,返回True
【注】都有axis参数:沿着哪一维度来求
x[x < 5]
x[x[:, -1] % 3 == 0, :] # 抽取行:最后一个特征值可以被3整除
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- azee.cn 版权所有 赣ICP备2024042794号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务