
第六章 数组基本操作
NumPy 提供了丰富而高效的数组基本操作,包括形状变换、维度调整、连接与分割、元素增删、翻转、对角线提取等。这些操作在数据预处理、图像处理、科学计算中极为常用。
reshape()返回一个具有新形状的视图(若可能),不改变原数组数据。
import numpy as np
a = np.arange(12) # [0 1 2 ... 11]
b = a.reshape(3, 4)
print(b)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
# 自动推断一个维度(用 -1)
c = a.reshape(2, -1) # 自动计算为 (2, 6)⚠️ 元素总数必须一致,否则报错。
resize()直接修改原数组形状(原地操作),若新尺寸更大,则用 0 填充。
a = np.array([1, 2, 3, 4])
a.resize(2, 3)
print(a)
# [[1 2 3]
# [4 0 0]] ← 自动填充0注意:
np.resize(a, new_shape)是函数形式,返回新数组,且会循环填充(不是补 0)!
d = np.resize([1,2], (2,3))
# [[1 2 1]
# [2 1 2]] ← 循环重复原始数据ravel() 与 flatten()将多维数组展平为一维:
方法 | 返回 | 是否共享内存 |
|---|---|---|
| 视图(若可能) | 是 |
| 副本 | 否 |
arr = np.array([[1, 2], [3, 4]])
print(arr.ravel()) # [1 2 3 4]
print(arr.flatten()) # [1 2 3 4]np.newaxis 或 Nonex = np.array([1, 2, 3]) # shape: (3,)
y = x[:, np.newaxis] # shape: (3, 1)
z = x[np.newaxis, :] # shape: (1, 3)squeeze()a = np.array([[[1], [2], [3]]]) # shape: (1, 3, 1)
b = a.squeeze() # shape: (3,)
c = a.squeeze(axis=0) # shape: (3, 1)expand_dims()x = np.array([1, 2, 3])
y = np.expand_dims(x, axis=1) # shape: (3, 1)np.concatenate()沿指定轴连接多个数组(要求其他维度一致)。
a = np.array([[1, 2], [3, 4]])
b = np.array([[5, 6]])
# 沿 axis=0(行方向)
np.concatenate([a, b], axis=0)
# [[1 2]
# [3 4]
# [5 6]]
# 沿 axis=1(列方向)→ 需要行数相同
c = np.array([[7], [8], [9]])
np.concatenate([a, c[:2]], axis=1) # 取前两行
# [[1 2 7]
# [3 4 8]]np.vstack():垂直堆叠(axis=0)np.hstack():水平堆叠(axis=1)np.dstack():深度堆叠(axis=2)np.vstack([a, b]) # 等价于 concatenate(..., axis=0)
np.hstack([a, [[7], [8]]]) # 列拼接💡 对一维数组:
vstack会将其视为行向量(自动升维)hstack直接拼接成更长的一维数组
np.split():等分或按位置分割arr = np.arange(9)
# 等分为3份
np.split(arr, 3) # [array([0,1,2]), array([3,4,5]), array([6,7,8])]
# 按索引位置分割
np.split(arr, [2, 5]) # 分成 [0:2], [2:5], [5:]np.hsplit():水平分割(axis=1)np.vsplit():垂直分割(axis=0)np.dsplit():深度分割(axis=2)mat = np.arange(12).reshape(3, 4)
np.hsplit(mat, 2) # 分成两个 (3,2) 数组⚠️ NumPy 数组大小固定,这些操作返回新数组,效率较低,应尽量避免频繁使用。
np.append()在末尾添加元素(自动展平!除非指定 axis)
a = np.array([1, 2, 3])
np.append(a, [4, 5]) # [1 2 3 4 5]
# 多维需指定 axis
b = np.array([[1, 2], [3, 4]])
np.append(b, [[5, 6]], axis=0) # 添加一行np.insert()在指定位置插入元素
a = np.array([1, 2, 4])
np.insert(a, 2, 3) # 在索引2处插入3 → [1 2 3 4]
np.insert(a, 1, [9, 10]) # 插入多个 → [1 9 10 2 4]np.delete()删除指定位置元素
a = np.array([1, 2, 3, 4])
np.delete(a, 1) # 删除索引1 → [1 3 4]
np.delete(a, [0,2]) # 删除多个 → [2 4]函数 | 说明 |
|---|---|
| 沿指定轴翻转 |
| 左右翻转(axis=1) |
| 上下翻转(axis=0) |
arr = np.array([[1, 2], [3, 4]])
np.fliplr(arr)
# [[2 1]
# [4 3]]
np.flipud(arr)
# [[3 4]
# [1 2]]
np.flip(arr, axis=None) # 完全翻转(等价于 arr[::-1, ::-1] 展平后反转)np.diag()v = np.array([1, 2, 3])
M = np.diag(v)
# [[1 0 0]
# [0 2 0]
# [0 0 3]]
np.diag(M) # [1 2 3]
np.diag(M, k=1) # 上对角线 → [0 0]np.diagonal()更通用的对角线提取(支持高维)
arr = np.arange(12).reshape(3, 4)
np.diagonal(arr) # [0 5 10]np.trace()计算对角线元素之和(迹)
np.trace(M) # 1+2+3 = 6arr = np.array([[1, 2, 3], [4, 5, 6]])
arr.T # 转置
arr.transpose() # 等价
np.transpose(arr, axes=(1,0)) # 显式指定轴顺序a = np.array([3, 1, 4, 1])
np.sort(a) # 返回排序后副本
a.sort() # 原地排序
np.argsort(a) # 返回排序索引操作类型 | 函数/方法 | 说明 |
|---|---|---|
形状变换 |
| 改变数组形状 |
维度调整 |
| 增删维度 |
连接 |
| 拼接数组 |
分割 |
| 拆分数组 |
增删元素 |
| (慎用) |
翻转 |
| 反转顺序 |
对角线 |
| 对角相关 |
转置 |
| 行列互换 |
这些操作构成了 NumPy 数据处理的基础。在实际项目中,优先使用向量化操作和视图机制,避免频繁创建新数组以提升性能。
图像通常表示为三维数组:(height, width, channels),例如 RGB 图像为 (H, W, 3)。
import numpy as np
# 模拟两张 100x100 的灰度图(单通道)
img1 = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8)
img2 = np.random.randint(0, 256, size=(100, 100), dtype=np.uint8)
# 水平拼接(左右并排)
combined = np.hstack([img1, img2]) # shape: (100, 200)
# 若是彩色图(H, W, 3),同样适用
color1 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
color2 = np.random.randint(0, 256, size=(100, 100, 3), dtype=np.uint8)
color_combined = np.hstack([color1, color2]) # (100, 200, 3)h, w = img1.shape
crop_h, crop_w = 50, 50
start_h, start_w = (h - crop_h) // 2, (w - crop_w) // 2
cropped = img1[start_h:start_h+crop_h, start_w:start_w+crop_w]✅ 切片是视图,内存高效!
深度学习框架(如 TensorFlow/PyTorch)要求输入为 (batch_size, height, width, channels)。
# 原始数据:1000 个样本,每个 784 维(如 MNIST 展平后的图像)
X_flat = np.random.rand(1000, 784)
# 重塑为 28x28 图像
X_img = X_flat.reshape(-1, 28, 28) # shape: (1000, 28, 28)
# 添加通道维度(灰度图 → (1000, 28, 28, 1))
X_img = X_img[..., np.newaxis] # 或 X_img.reshape(-1, 28, 28, 1)
print(X_img.shape) # (1000, 28, 28, 1)single_sample = np.random.rand(28, 28)
batch_input = np.expand_dims(single_sample, axis=0) # (1, 28, 28)将一维时间序列分割为多个重叠窗口,用于 LSTM 或特征提取。
reshape + stride_tricks 或简单循环实现滑动窗口def create_sliding_windows(data, window_size, step=1):
"""
将一维数组分割为滑动窗口
"""
n = len(data)
num_windows = (n - window_size) // step + 1
windows = []
for i in range(0, num_windows * step, step):
windows.append(data[i:i+window_size])
return np.array(windows)
# 使用
ts = np.arange(10) # [0 1 2 ... 9]
windows = create_sliding_windows(ts, window_size=4, step=2)
print(windows)
# [[0 1 2 3]
# [2 3 4 5]
# [4 5 6 7]
# [6 7 8 9]]💡 更高效方式可用
numpy.lib.stride_tricks.sliding_window_view(NumPy ≥1.20):
from numpy.lib.stride_tricks import sliding_window_view
windows = sliding_window_view(ts, window_shape=4)[::2] # 步长为2在物理模拟、优化问题中常需构造或操作对角矩阵。
n = 5
main_diag = np.full(n, 2.0)
off_diag = np.full(n-1, -1.0)
# 构造三对角矩阵
A = np.diag(main_diag) + np.diag(off_diag, k=1) + np.diag(off_diag, k=-1)
print(A)
# [[ 2. -1. 0. 0. 0.]
# [-1. 2. -1. 0. 0.]
# [ 0. -1. 2. -1. 0.]
# [ 0. 0. -1. 2. -1.]
# [ 0. 0. 0. -1. 2.]]cov_matrix = np.array([[1.0, 0.2, 0.1],
[0.2, 2.0, 0.3],
[0.1, 0.3, 1.5]])
variances = np.diag(cov_matrix) # [1.0, 2.0, 1.5]在训练 CNN 时,通过对图像翻转增加数据多样性。
image = np.random.rand(32, 32, 3)
# 水平翻转(左右镜像)
flipped_lr = np.fliplr(image)
# 垂直翻转(上下颠倒)
flipped_ud = np.flipud(image)
# 随机选择是否翻转(用于数据增强 pipeline)
if np.random.rand() > 0.5:
image = np.fliplr(image)✅ 这些操作返回视图或高效副本,适合实时增强。
多个传感器采集相同时间长度的数据,需合并处理。
# 模拟3个传感器,各采样100个时间点
sensor1 = np.random.randn(100)
sensor2 = np.random.randn(100)
sensor3 = np.random.randn(100)
# 合并为 (100, 3) 的特征矩阵
features = np.column_stack([sensor1, sensor2, sensor3]) # 等价于 hstack 升维后
# 或者用 vstack 转置
features_alt = np.vstack([sensor1, sensor2, sensor3]).T # shape: (100, 3)
# 分割回原始信号
s1, s2, s3 = features.T # 利用转置解包应用场景 | 推荐 NumPy 操作 |
|---|---|
图像拼接 |
|
深度学习输入准备 |
|
时间序列窗口 |
|
物理/数学建模 |
|
数据增强 |
|
多源数据融合 |
|
本文主要讲述了numpy数组的基本操作以及应用场景。python过渡项目部分代码已经上传至gitee,后续会逐步更新,主要受时间原因限制,当然自己也可以克隆到本地学习拓展。
公众号:咚咚王
《Python编程:从入门到实践》
《利用Python进行数据分析》
《算法导论中文第三版》
《概率论与数理统计(第四版) (盛骤) 》
《程序员的数学》
《线性代数应该这样学第3版》
《微积分和数学分析引论》
《(西瓜书)周志华-机器学习》
《TensorFlow机器学习实战指南》
《Sklearn与TensorFlow机器学习实用指南》
《模式识别(第四版)》
《深度学习 deep learning》伊恩·古德费洛著 花书
《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》
《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen)》
《自然语言处理综论 第2版》
《Natural-Language-Processing-with-PyTorch》
《计算机视觉-算法与应用(中文版)》
《Learning OpenCV 4》
《AIGC:智能创作时代》杜雨+&+张孜铭
《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》
《从零构建大语言模型(中文版)》
《实战AI大模型》
《AI 3.0》
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。