人工智能之数据分析 numpy:第六章 数组基本操作

人工智能之数据分析 numpy

第六章 数组基本操作


@

目录
  • 人工智能之数据分析 numpy
  • 前言
  • 一、修改数组形状(Reshaping)
    • 1. reshape()
    • 2. resize()
    • 3. ravel()flatten()
  • 二、修改维度(Adding/Removing Axes)
    • 1. 增加维度:np.newaxisNone
    • 2. 删除长度为 1 的维度:squeeze()
    • 3. 扩展维度:expand_dims()
  • 三、数组连接(Concatenation)
    • 1. np.concatenate()
    • 2. 快捷函数
  • 四、数组分割(Splitting)
    • 1. np.split():等分或按位置分割
    • 2. 方向专用函数
  • 五、增减元素
    • 1. np.append()
    • 2. np.insert()
    • 3. np.delete()
  • 六、翻转数组(Flipping)
  • 七、对角线操作
    • 1. np.diag()
    • 2. np.diagonal()
    • 3. np.trace()
  • 八、其他实用操作
    • 转置(Transpose)
    • 排序
  • 九、小结表:常用操作速查
  • 📌 场景 1:图像处理 —— 图像拼接与裁剪
    • 背景
    • 示例:水平拼接两张图像(如对比原图与滤波结果)
    • 裁剪图像中心区域(使用切片)
  • 📌 场景 2:机器学习 —— 批量数据 reshape 与维度扩展
    • 背景
    • 示例:将一维特征向量转为“伪图像”用于 CNN
    • 增加 batch 维度(单样本推理)
  • 📌 场景 3:时间序列分析 —— 滑动窗口分割
    • 背景
    • 示例:用 reshape + stride_tricks 或简单循环实现滑动窗口
  • 📌 场景 4:科学计算 —— 构造对角矩阵与提取对角线
    • 背景
    • 示例:构建带状对角矩阵(如有限差分法中的 Laplacian)
    • 提取协方差矩阵的方差(对角线)
  • 📌 场景 5:数据增强 —— 翻转图像(数据扩增)
    • 背景
  • 📌 场景 6:多传感器数据融合 —— 数组连接与分割
    • 背景
  • 总结:按场景推荐操作
  • 后续
  • 资料关注


前言

NumPy 提供了丰富而高效的​数组基本操作​,包括形状变换、维度调整、连接与分割、元素增删、翻转、对角线提取等。这些操作在数据预处理、图像处理、科学计算中极为常用。


一、修改数组形状(Reshaping)

1. reshape()

返回一个具有新形状的​视图​(若可能),不改变原数组数据。

import numpy as npa = 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)

⚠️ 元素总数必须一致,否则报错。

2. 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]]  ← 循环重复原始数据

3. ravel()flatten()

将多维数组展平为一维:

方法 返回 是否共享内存
ravel() 视图(若可能)
flatten() 副本
arr = np.array([[1, 2], [3, 4]])
print(arr.ravel())    # [1 2 3 4]
print(arr.flatten())  # [1 2 3 4]

二、修改维度(Adding/Removing Axes)

1. 增加维度:np.newaxisNone

x = np.array([1, 2, 3])      # shape: (3,)
y = x[:, np.newaxis]         # shape: (3, 1)
z = x[np.newaxis, :]         # shape: (1, 3)

2. 删除长度为 1 的维度:squeeze()

a = np.array([[[1], [2], [3]]])  # shape: (1, 3, 1)
b = a.squeeze()                  # shape: (3,)
c = a.squeeze(axis=0)            # shape: (3, 1)

3. 扩展维度:expand_dims()

x = np.array([1, 2, 3])
y = np.expand_dims(x, axis=1)  # shape: (3, 1)

三、数组连接(Concatenation)

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]]

2. 快捷函数

  • 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 直接拼接成更长的一维数组

四、数组分割(Splitting)

1. 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:]

2. 方向专用函数

  • 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 数组大小固定,这些操作​返回新数组​,效率较低,应尽量避免频繁使用。

1. 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)  # 添加一行

2. 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]

3. np.delete()

删除指定位置元素

a = np.array([1, 2, 3, 4])
np.delete(a, 1)     # 删除索引1 → [1 3 4]
np.delete(a, [0,2]) # 删除多个 → [2 4]

六、翻转数组(Flipping)

函数 说明
np.flip(arr, axis) 沿指定轴翻转
np.fliplr(arr) 左右翻转(axis=1)
np.flipud(arr) 上下翻转(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] 展平后反转)

七、对角线操作

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]

2. np.diagonal()

更通用的对角线提取(支持高维)

arr = np.arange(12).reshape(3, 4)
np.diagonal(arr)  # [0 5 10]

3. np.trace()

计算对角线元素之和(迹)

np.trace(M)  # 1+2+3 = 6

八、其他实用操作

转置(Transpose)

arr = 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)    # 返回排序索引

九、小结表:常用操作速查

操作类型 函数/方法 说明
形状变换 reshape,resize,ravel,flatten 改变数组形状
维度调整 np.newaxis,squeeze,expand_dims 增删维度
连接 concatenate,vstack,hstack 拼接数组
分割 split,hsplit,vsplit 拆分数组
增删元素 append,insert,delete (慎用)
翻转 flip,fliplr,flipud 反转顺序
对角线 diag,diagonal,trace 对角相关
转置 .T,transpose() 行列互换

这些操作构成了 NumPy 数据处理的基础。在实际项目中,​优先使用向量化操作和视图机制​,避免频繁创建新数组以提升性能。

📌 场景 1:图像处理 —— 图像拼接与裁剪

背景

图像通常表示为三维数组:(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]

✅ 切片是视图,内存高效!


📌 场景 2:机器学习 —— 批量数据 reshape 与维度扩展

背景

深度学习框架(如 TensorFlow/PyTorch)要求输入为 (batch_size, height, width, channels)

示例:将一维特征向量转为“伪图像”用于 CNN

# 原始数据: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)

增加 batch 维度(单样本推理)

single_sample = np.random.rand(28, 28)
batch_input = np.expand_dims(single_sample, axis=0)  # (1, 28, 28)

📌 场景 3:时间序列分析 —— 滑动窗口分割

背景

将一维时间序列分割为多个重叠窗口,用于 LSTM 或特征提取。

示例:用 reshape + stride_tricks 或简单循环实现滑动窗口

def create_sliding_windows(data, window_size, step=1):"""将一维数组分割为滑动窗口"""n = len(data)num_windows = (n - window_size) // step + 1windows = []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

📌 场景 4:科学计算 —— 构造对角矩阵与提取对角线

背景

在物理模拟、优化问题中常需构造或操作对角矩阵。

示例:构建带状对角矩阵(如有限差分法中的 Laplacian)

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]

📌 场景 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)

✅ 这些操作返回视图或高效副本,适合实时增强。


📌 场景 6:多传感器数据融合 —— 数组连接与分割

背景

多个传感器采集相同时间长度的数据,需合并处理。

# 模拟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 操作
图像拼接 np.hstack,np.vstack
深度学习输入准备 reshape,expand_dims,np.newaxis
时间序列窗口 sliding_window_view, 自定义切片
物理/数学建模 np.diag,np.diagonal
数据增强 np.fliplr,np.flipud,np.flip
多源数据融合 np.column_stack,np.concatenate,.T

后续

本文主要讲述了numpy数组的基本操作以及应用场景。python过渡项目部分代码已经上传至gitee,后续会逐步更新,主要受时间原因限制,当然自己也可以克隆到本地学习拓展。

资料关注

公众号:咚咚王
gitee:https://gitee.com/wy18585051844/ai_learning

《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》

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/974073.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025中山办公场地租赁优选:中山西区金嘉创新港,一站式创业空间,赋能企业成长新机遇

随着中山市产业升级与创新创业浪潮的蓬勃发展,优质办公空间已成为企业发展的重要基石。在2025年中山商业地产市场中,中山西区金嘉创新港凭借多元化的空间解决方案、完善的配套服务体系及卓越的区位优势,成为各类企业…

国产数据库替代MongoDB:政务电子证照新选择 - 教程

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

读书笔记《投资的未来》,估算收益率

比较IBM和新泽西标准石油两家公司,一个新兴的,受追捧的,一个传统的,但结果,是石油公司胜出。尽管两只股票的业绩都不错,但是1950~2003年,新泽西标准石油的投资者每年可以取得14.42%的年收益率,这比IBM提供的1…

使用代码查询快递信息的方法(与查询天气的方式雷同)

第一步:在标签中添加JS文件具体内容如下:第二步:写出大概的框架第三步:写JS部分(1)定义appkey和API地址(2)校验输入和显示加载状态(3)调用API和解析返回数据(4)展示拼接内容和判断内容是否正确第四步:保存并运行查…

1101. Quick Sort (25)

1101. Quick Sort (25)#include <iostream> #include <vector> #include <algorithm>using namespace std;int num[100010], low[100010], high[100010];int main() {int n;scanf("%d", &…

1100. Mars Numbers (20)

1100. Mars Numbers (20)#include <iostream> #include <string.h>using namespace std;char ch[2][13][5] = {"tret", "jan", "feb", "mar", "apr",…

解码网络编程基础

进程间通信方式 基础概念 程序是数据和指令的集合,运行时成为进程,操作系统会为其分配资源并记录参数。同一主机内进程通信可通过管道、信号、消息队列、信号量集、共享内存实现,这些方式依赖主机本地系统资源,无法…

C++的3种继承方式

C++的3种继承方式 在 C++ 中,继承方式(public、protected、private)决定了基类成员在派生类中的访问权限,以及派生类对象对基类成员的访问权限。正确选择继承方式是实现封装、复用和多态的关键。以下是三种继承方式…

1082. Read Number in Chinese (25)

1082. Read Number in Chinese (25)#include <iostream> #include <string.h>using namespace std;int first = 1;void setfirst() {if(first == 1){first = 0;}else{printf(" ");} }int main()…

1081. Rational Sum (20)

1081. Rational Sum (20)#include <iostream>using namespace std;long long getsame(long long a, long long b) {if(b != 0){return getsame(b, a % b);}else{return a;} }void simplify(long long &a, lo…

1067. Sort with Swap(0) (25)

1067. Sort with Swap(0) (25)#include <iostream>using namespace std;int index[100010], num[100010];int main() {int n;scanf("%d", &n);int i, count = 0;for(i = 0; i < n; i++){scanf(…

1066. Root of AVL Tree (25)

1066. Root of AVL Tree (25)#include <iostream> #include <stdlib.h>using namespace std;typedef struct node {int key, bf;struct node *lchild, *rchild; }*bnode;void rrotate(bnode *root) {bnode…

1070. Mooncake (25)

1070. Mooncake (25)#include <iostream> #include <algorithm>using namespace std;struct node {double amounts, prices, perprice; }mooncakes[1010];int cmp(node n1, node n2) {return n1.perprice …

1069. The Black Hole of Numbers (20)

1069. The Black Hole of Numbers (20)#include <iostream> #include <string.h> #include <algorithm>using namespace std;int cmp(char a, char b) {return a > b; }int main() {int num[2];s…

1050. String Subtraction (20)

1050. String Subtraction (20)#include <iostream> #include <string.h>using namespace std;int flag[130]; char s[2][10010];int main() {int i, len[2];for(i = 0; i <= 1; i++){gets(s[i]);len[i…

1049. Counting Ones (30)

1049. Counting Ones (30)#include <iostream>using namespace std;int main() {int n;scanf("%d", &n);int low, mid, high, d = 1, res = 0;while(n >= d){high = n / (d * 10);mid = (n - h…

1045. Favorite Color Stripe (30)

1045. Favorite Color Stripe (30)#include <iostream>using namespace std;int fav[210], ori[10010], res[210][10010];int getmax(int a, int b) {if(a > b){return a;}else{return b;} }int main() {int …

1048. Find Coins (25)

1048. Find Coins (25)#include <iostream> #include <algorithm>using namespace std;int c[510], num[100010];int main() {int n, m;scanf("%d%d", &n, &m);int i;for(i = 1; i <…

1052. Linked List Sorting (25)

1052. Linked List Sorting (25)#include <iostream> #include <algorithm> #include <vector>using namespace std;struct node {int address, key, next; }nod[100000];int cmp(node n1, node n2)…

1051. Pop Sequence (25)

1051. Pop Sequence (25)#include <iostream> #include <stack>using namespace std;int main() {int m, n, k;scanf("%d%d%d", &m, &n, &k);int i, num[1010], j, index, flag, be…