第七章 数组迭代排序筛选
在 NumPy 中, 数组的迭代、排序与筛选是数据处理中的三大基础操作。虽然 NumPy 强调 向量化操作(避免显式 Python 循环以提升性能),但在某些场景下仍需对数组进行迭代(如逐行/逐元素处理)。本文将系统讲解这三类操作,并结合实际示例说明如何高效使用。
但若必须迭代,NumPy 提供了多种方式:
import numpy as np a = np.array([1, 2, 3]) for x in a: print(x) # 1, 2, 3
b = np.array([[1, 2], [3, 4]]) for row in b: print(row) # [1 2], [3 4]
np.nditer()适用于任意维度,内存高效(支持 C/Fortran 顺序)。
c = np.array([[1, 2], [3, 4]]) # 只读迭代 for x in np.nditer(c): print(x, end=' ') # 1 2 3 4 # 可写迭代(修改原数组) with np.nditer(c, op_flags=['readwrite']) as it: for x in it: x[...] = x * 2 print(c) # [[2 4] [6 8]]
a = np.array([1, 2, 3]) b = np.array([10, 20, 30]) for x, y in np.nditer([a, b]): print(x, y) # (1,10), (2,20), (3,30)
np.ndenumerate()d = np.array([[10, 20], [30, 40]]) for index, value in np.ndenumerate(d): print(index, value) # (0,0) 10 # (0,1) 20 # (1,0) 30 # (1,1) 40
✅ 最佳实践:除非逻辑复杂无法向量化,否则不要用
for循环处理 NumPy 数组!
arr = np.array([3, 1, 4, 1, 5]) # 返回排序后新数组 sorted_arr = np.sort(arr) # 原地排序 arr.sort() # 获取排序索引 indices = np.argsort(arr) # [1 3 0 2 4]
mat = np.array([[3, 1], [2, 4]]) # 按行排序(每行内部排) np.sort(mat, axis=1) # [[1 3], [2 4]] # 按列排序(每列内部排) np.sort(mat, axis=0) # [[2 1], [3 4]]
dt = np.dtype([('name', 'U10'), ('score', 'i4')])
students = np.array([('Alice', 85), ('Bob', 90), ('Charlie', 78)], dtype=dt)
# 按 score 排序
sorted_students = np.sort(students, order='score')
print(sorted_students)
# [('Charlie', 78) ('Alice', 85) ('Bob', 90)]
data = np.array([10, 20, 30, 40, 50]) # 单条件 filtered = data[data > 30] # [40 50] # 多条件(注意括号!) filtered = data[(data > 20) & (data < 50)] # [30 40] # 非(not) filtered = data[~(data == 30)] # [10 20 40 50]
np.where() 筛选索引# 返回满足条件的索引 indices = np.where(data > 30) # (array([3, 4]),) values = data[indices] # [40 50] # 三元选择(类似 if-else) result = np.where(data > 30, data, -1) # [ -1 -1 -1 40 50]
# 按指定位置筛选 positions = [0, 2, 4] selected = data[positions] # [10 30 50]
# 创建结构化数组:姓名、数学、英语成绩
dt = np.dtype([('name', 'U10'), ('math', 'f4'), ('english', 'f4')])
scores = np.array([
('Alice', 88, 92),
('Bob', 75, 85),
('Charlie', 95, 88),
('Diana', 60, 90)
], dtype=dt)
# 1️⃣ 筛选:找出数学 > 80 的学生
good_math = scores[scores['math'] > 80]
print("数学优秀:\n", good_math)
# 2️⃣ 排序:按总分降序排列
total = scores['math'] + scores['english']
sorted_indices = np.argsort(-total) # 负号实现降序
ranked = scores[sorted_indices]
print("排名:\n", ranked)
# 3️⃣ 迭代:打印每位学生的总分(仅用于演示,实际应向量化)
print("总分列表:")
for student in scores:
print(f"{student['name']}: {student['math'] + student['english']}")
# ✅ 更高效写法(无循环):
print("总分(向量化):", scores['math'] + scores['english'])
输出:
数学优秀:
[('Alice', 88., 92.) ('Charlie', 95., 88.)]
排名:
[('Alice', 88., 92.) ('Charlie', 95., 88.) ('Bob', 75., 85.) ('Diana', 60., 90.)]
总分列表:
Alice: 180.0
Bob: 160.0
Charlie: 183.0
Diana: 150.0
总分(向量化): [180. 160. 183. 150.]
# 模拟灰度图像(0~255)
img = np.random.randint(0, 256, size=(4, 4), dtype=np.uint8)
print("原图:\n", img)
# 筛选:只保留亮度 > 128 的像素,其余设为0
bright_pixels = np.where(img > 128, img, 0)
print("高亮区域:\n", bright_pixels)
# 排序:获取所有像素值的排序
flat_sorted = np.sort(img.ravel())
print("所有像素排序:", flat_sorted)
# 迭代:统计每个灰度级出现次数(实际应用中用 np.bincount 更高效)
hist = np.zeros(256, dtype=int)
for pixel in np.nditer(img):
hist[pixel] += 1
print("直方图(前10个):", hist[:10])
💡 实际图像处理中,应使用
np.histogram()或cv2.calcHist(),而非手动迭代。
large_arr = np.random.rand(1_000_000) # ✅ 向量化(快) result_vec = large_arr[large_arr > 0.5] # ❌ 显式循环(慢) result_loop = [] for x in large_arr: if x > 0.5: result_loop.append(x)
在 100 万数据上,向量化通常比 Python 循环快 10\~100 倍!
| 操作 | 推荐方式 | 避免方式 |
| ---------------- | --------------------------------------------------- | ----------------------------- |
|
迭代 |
np.nditer,
np.ndenumerate(仅必要时) | 普通
for 循环处理大数组 |
|
排序 |
np.sort,
argsort,
order(结构化) | 手动实现排序算法 |
|
筛选 | 布尔索引、
np.where | 用循环逐个判断 |
🔑 核心思想: 尽可能用 NumPy 内置函数替代 Python 循环,以发挥其 C 语言底层优化的优势。
本文主要讲述了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》
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048224/viewspace-3103058/ ,如需转载,请注明出处,否则将追究法律责任。