如何在Python中提取并删除二维NumPy数组的指定索引区间
解决二维矩阵按全局索引区间删除元素并保留结构的问题
核心思路
先把二维矩阵扁平化,筛选出需要保留的全局索引,提取对应元素后再重塑回原行数的二维结构。
具体实现代码
import numpy as np # 示例矩阵 a = np.array([[12, 4, 35, 0, 26, 15, 100], [17, 37, 29, 87, 46, 95, 120]]) # 1. 定义要删除的全局索引区间 # 区间2-5(包含两端)、8-10(包含两端) delete_ranges = [np.arange(2, 6), np.arange(8, 11)] delete_indices = np.concatenate(delete_ranges) # 2. 生成所有全局索引,筛选出需要保留的索引 all_indices = np.arange(a.size) keep_indices = np.setdiff1d(all_indices, delete_indices) # 3. 提取保留元素并重塑为原行数的二维结构 result = a.flatten()[keep_indices].reshape(a.shape[0], -1) print(result)
输出结果
[[ 12 4 100] [ 17 46 95 120]]
关键步骤说明
- 用
flatten()把二维矩阵转成一维数组,方便按全局索引操作 np.setdiff1d用来找出所有索引中不在删除列表里的保留索引reshape(a.shape[0], -1)保证最终结果还是2行的二维结构,列数自动根据剩余元素数计算
内容的提问来源于stack exchange,提问作者user3901294
相关产品推荐
相关产品推荐

