You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在多维NumPy数组中从坐标列表提取切片且不修改原数组?

嘿,我懂你想要的效果——不用修改原数组,也不用复制它,直接从给定的切片列表获取对应的坐标索引对吧?这确实是个更优雅的做法,毕竟修改原数组可能会带来副作用,尤其是在处理大数组的时候。

这里有两种高效的矢量化方法可以实现你的需求,完全不会触碰原数组:

方法一:利用np.indices生成索引网格

np.indices可以直接生成对应数组形状的各维度索引网格,我们只需要用你的切片列表提取出目标区域,再整理成坐标列表即可:

import numpy as np

# 原数组的形状(不需要实际创建数组)
base_shape = (8, 8, 4)
# 你的切片列表
coord = [slice(0, 1, None), slice(0, None, None)]

# 先补全切片到所有维度(如果切片列表长度小于数组维度,默认补全为全选)
full_coord = coord + [slice(None)] * (len(base_shape) - len(coord))

# 生成对应切片区域的各维度索引
indices = np.indices(base_shape)[tuple(full_coord)]

# 将索引堆叠成(N, 3)的格式,和np.argwhere输出一致
result = np.stack(indices, axis=-1).reshape(-1, len(base_shape))

方法二:用np.meshgrid手动生成坐标网格

如果你更倾向于分步生成每个维度的坐标,也可以用np.meshgrid来实现,同样是矢量化操作:

import numpy as np

base_shape = (8, 8, 4)
coord = [slice(0, 1, None), slice(0, None, None)]
full_coord = coord + [slice(None)] * (len(base_shape) - len(coord))

# 生成每个维度在切片范围内的坐标数组
dim_coords = []
for dim_idx, slc in enumerate(full_coord):
    dim_coords.append(np.arange(base_shape[dim_idx])[slc])

# 生成索引网格(注意用indexing='ij'匹配NumPy的索引顺序)
coord_grid = np.meshgrid(*dim_coords, indexing='ij')

# 整理成坐标列表
result = np.stack(coord_grid, axis=-1).reshape(-1, len(base_shape))

效果验证

运行上面的代码后,result的输出格式和你原来用np.argwhere(base == -1)得到的结果完全一致,但全程没有创建或修改原数组,完美符合你的需求。

内容的提问来源于stack exchange,提问作者Andrew Fells

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:39:22