ndarray
import numpy as np
a = np.array([[1,2,3,4,5],
[9,8,7,6,5]])
print(a)
轴(axis):数据的维度 秩(rank):轴的数量
ndarray对象的属性
属性 | 说明 |
---|---|
.ndim | 秩,即轴的数量,或维度的数量 |
.shape | ndarray对象的尺度,对于矩阵表示n行m列 |
.size | ndaaray对象元素的个数,相当于n*m的值 |
.dtype | 对象的元素类型 |
.itemsize | ndarray对象中每个元素的大小,以字节为单位 |
使用nuympy函数创建ndarray
函数 | 说明 |
---|---|
np.arange(n) | 0到n-1 |
np.ones(shape) | 生成一个全一的数组,shape是一个元组类型 |
np.zeros(shape) | 生成一个全零的数组,shape是一个元组类型 |
np.emty(shape) | 生成近似于空的数组 |
np.full(shape,val) | 每个元素值都是val |
np.eye(n) | 生成一个n*n单位矩阵,对角线为1,其余全0 |
np.ones_like(nparry) | 生成一个和目标相同shape的全一数组 |
np.zeros_like(nparry) | |
np.empty_like(nparry) | |
np.full_like(nparry,val) | |
np.linspace(start, stop, num=50, endpoint=True) | 等间距生成数组 |
np.concatenate(a,b) | 合并两个数组成一个 |
维度变换方法
函数 | 说明 |
---|---|
.reshape((a, newshape, order=’C’)) | 不改变数组元素,返回一个newshape形状的数组 |
.resize(shape) | 与reshape一样,不过修改原数组 |
.swapaxes(ax1,ax2) | 将两个维度进行调换 |
.platten() | 降维 |
代码实例
a = np.arange(6).reshape((3, 2))
a # array([[0, 1],
[2, 3],
[4, 5]])
a.flatten() #array([0,1, 2, 3, 4, 5])
数组的索引和切片
"""索引 """
a = np.arange(24).reshape(2,3,4)
a
#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]]])
a[1,2,3] #23
a[1,2,-1] # 23
""" 切片 """
a[:,1,-3] # 5,17
a[:,1:3,:]
#array([[[ 4, 5, 6, 7],
[ 8, 9, 10, 11]],
[[16, 17, 18, 19],
[20, 21, 22, 23]]])
a[:,:,::2] # ::2表示步长跳跃
#array([[[ 0, 2],
[ 4, 6],
[ 8, 10]],
[[12, 14],
[16, 18],
[20, 22]]])
""" 运算 """
""" 数组与标量的计算,对应到a中每一个元素,略 """
一元函数
函数 | 说明 |
---|---|
np.abs() | 绝对值 |
np.sqrt() | 平方根 |
np.square() | 平方 |
np.log() np.log10() np.log2() | 对数 |
np.ceiling() np.floor() | ceiling是进一 floor是退一 |
np.rint | 四舍五入整数 |
np.modf(x) | 将数组的小数和整数部分已两个独立数组返回 |
np.sin(x) … | 三角函数 |
np.exp(x) | 指数函数 |
np.sign(x) | 返回各元素的符号 正负号 |
二元函数
函数 | 说明 |
---|---|
+-*/ ** | |
np.maximum(x,y) np.fmax() | |
np.minimum(x,y) np.fmin() | |
np.mod(x,y) | |
np.copysign(x,y) | 把y的符号赋给x |
>< >= <= == != | 算数比较,产生一个布尔数组 |