NumPy库向量的常见运算
创建向量
import numpy as np# 从列表创建向量
v = np.array([1, 2, 3])# 创建全零向量
zeros = np.zeros(3) # [0., 0., 0.]# 创建全一向量
ones = np.ones(3) # [1., 1., 1.]# 创建等差向量
arange = np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
linspace = np.linspace(0, 1, 5) # [0., 0.25, 0.5, 0.75, 1.]# 创建随机向量
random = np.random.rand(3) # 3个[0,1)区间的随机数print(v, zeros, ones, arange, linspace, random)
其中np.arange语法
numpy.arange(start, stop, step, dtype=None)
start
:序列起始值(包含),默认为 0stop
:序列结束值(不包含)step
:步长(间隔),默认为 1dtype
:输出数组的数据类型
import numpy as np# 从0开始,到5结束(不包含),步长为1
print(np.arange(5)) # [0 1 2 3 4]# 从1开始,到10结束(不包含),步长为2
print(np.arange(1, 10, 2)) # [1 3 5 7 9]# 使用浮点数步长
print(np.arange(0, 1, 0.2)) # [0. 0.2 0.4 0.6 0.8]# 指定数据类型
print(np.arange(5, dtype=float)) # [0. 1. 2. 3. 4.]
其中np.linspace
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
start
:序列起始值stop
:序列结束值num
:要生成的样本数,默认为 50endpoint
:是否包含结束值,默认为 Trueretstep
:如果为 True,返回 (samples, step)dtype
:输出数组的数据类型
# 从0到1,生成5个等间距点(默认包含结束点)
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]# 不包含结束点
print(np.linspace(0, 1, 5, endpoint=False)) # [0. 0.2 0.4 0.6 0.8]# 获取步长信息
samples, step = np.linspace(0, 1, 5, retstep=True)
print(step) # 0.25# 生成整数序列
print(np.linspace(0, 10, 5, dtype=int)) # [ 0 2 5 7 10]
基本数学运算
import numpy as npa = np.array([1, 2, 3])
b = np.array([4, 5, 6])# 逐元素加法
sum = a + b # [5, 7, 9]# 逐元素减法
diff = a - b # [-3, -3, -3]# 逐元素乘法
prod = a * b # [4, 10, 18]# 逐元素除法
quot = b / a # [4., 2.5, 2.]# 标量乘法
scaled = 2 * a # [2, 4, 6]# 逐元素平方
squared = a ** 2 # [1, 4, 9]# 逐元素指数
exp = np.exp(a) # [2.718, 7.389, 20.085]print(sum, diff, prod, quot, scaled, squared, exp)
向量运算
import numpy as npa = np.array([1, 2, 3])
b = np.array([4, 5, 6])# 点积(内积)
dot_product = np.dot(a, b) # 1*4 + 2*5 + 3*6 = 32
# 或使用 @ 运算符
dot_product = a @ b# 叉积(仅适用于3D向量)
# 计算公式:[a1 * b2 - a2 * b1, a2 * b0 - a0 * b2, a0 * b1 - a1 * b0]
cross_product = np.cross([1, 0, 0], [0, 1, 0]) # [0, 0, 1]# 向量范数(长度)
norm = np.linalg.norm(a) # sqrt(1² + 2² + 3²) ≈ 3.7417# 单位向量
unit_vector = a / np.linalg.norm(a)# 元素求和
total = np.sum(a) # 6# 元素累积和
cumsum = np.cumsum(a) # [1, 3, 6]print(dot_product, cross_product, norm, unit_vector, total, cumsum)
其中np.cumsum
numpy.cumsum(a, axis=None, dtype=None, out=None)
a: 输入数组
axis: 沿着哪个轴计算累积和(None表示展平数组后计算)
dtype: 返回数组的数据类型
out: 可选输出数组,用于存放结果
统计运算
import numpy as npa = np.array([1, 2, 3])# 均值
mean = np.mean(a) # 2.0# 方差
variance = np.var(a) # 0.666...# 标准差
std_dev = np.std(a) # 0.816...# 最大值
max_val = np.max(a) # 3# 最小值
min_val = np.min(a) # 1# 最大值索引
max_index = np.argmax(a) # 2# 最小值索引
min_index = np.argmin(a) # 0print(mean, variance, std_dev, max_val, min_val, max_index, min_index)
逻辑运算
import numpy as npa = np.array([1, 2, 3])# 元素比较
mask = a > 1 # [False, True, True]# 任意元素为True
any_true = np.any(mask) # True# 所有元素为True
all_true = np.all(mask) # False# 条件选择
selected = np.where(a > 1, a, 0) # [0, 2, 3]print(mask, any_true, all_true, selected)
其中np.where语法,np.where(condition, x, y)
= "如果 condition 成立,取 x,否则取 y",是 NumPy 里最常用的条件替换函数!
返回满足条件的元素的索引
indices = np.where(condition)
import numpy as nparr = np.array([1, 2, 3, 2, 4, 2])
indices = np.where(arr == 2)
print(indices) # (array([1, 3, 5]),) 返回一个元组# 获取满足条件的元素
print(arr[indices]) # [2 2 2]# 多维数组示例
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
rows, cols = np.where(arr2d > 3)
print(rows) # [1 1 1]
print(cols) # [0 1 2]
条件替换
result = np.where(condition, x, y)
当condition为True时,取x中对应位置的值
当condition为False时,取y中对应位置的值
import numpy as nparr = np.array([1, 2, 3, 4, 5])
result = np.where(arr > 3, arr, 0) # 大于3的值保留,其余替换为0
print(result) # [0 0 0 4 5]# 使用不同数组
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
cond = np.array([True, False, True, False])
result = np.where(cond, a, b)
print(result) # [1 20 3 40]
广播机制
import numpy as nparr = np.array([[1, 2, 3], [4, 5, 6]])
# -1被扩展成[[-1, -1, -1],[-1, -1, -1]]
result = np.where(arr > 3, arr, -1) # 标量会被广播
print(result)
# [[-1 -1 -1]
# [ 4 5 6]]
向量操作
import numpy as npa = np.array([1, 2, 3])
b = np.array([4, 5, 6])# 向量拼接
concat = np.concatenate([a, b]) # [1, 2, 3, 4, 5, 6]# 向量分割
split = np.split(concat, 3) # [array([1, 2]), array([3, 4]), array([5, 6])]# 向量排序
sorted_arr = np.sort([3, 1, 2]) # [1, 2, 3]# 向量反转
reversed_arr = a[::-1] # [3, 2, 1]# 向量重塑
reshaped = a.reshape(3, 1) # 3x1列向量print(concat, split, sorted_arr, reversed_arr, reshaped)
其中np.split
numpy.split(ary, indices_or_sections, axis=0)
按均匀分割
import numpy as nparr = np.arange(9) # [0 1 2 3 4 5 6 7 8]
result = np.split(arr, 3)
print(result)
# [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]
按指定位置分割
import numpy as nparr = np.arange(10) # [0 1 2 3 4 5 6 7 8 9]
result = np.split(arr, [3, 5, 8])
print(result)
# [array([0, 1, 2]),
# array([3, 4]),
# array([5, 6, 7]),
# array([8, 9])]