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

是否有Numpy函数可在多维数组中查找指定行并获取其索引?

Numpy检查指定行是否存在并获取索引的实现方法

你可以直接用numpy内置函数完成需求,以下是两种常用实现方案:

方案1:广播全匹配(适合中小规模数组)

直接利用numpy的广播机制对每行的所有元素做等值判断,实现逻辑简单易懂:

import numpy as np

# 示例数组
arr = np.array([
    [1,0,8,7,2,2],
    [1,3,7,0,3,0],
    [1,7,1,0,1,0],
    [1,9,1,0,6,0],
    [1,8,1,7,9,0]
])
# 要查找的目标行
target = np.array([6,0,5,8,2,1])

# 逐行判断是否完全匹配
matches = np.all(arr == target, axis=1)
# 判断是否存在匹配行
exists = np.any(matches)
# 获取匹配行的索引,返回空数组则说明无匹配
indices = np.where(matches)[0]

print(f"是否存在:{exists}")
print(f"匹配的行索引:{indices}")

方案2:结构化数组视图(适合大规模数组)

如果你的数组行数非常多,方案1的广播机制会产生较大的临时内存开销,可以用视图转换的方式优化性能,运算效率会高很多:

# 接上面的arr和target定义
# 把每行转成一个单一的结构化元素
arr_view = arr.view(np.dtype((np.void, arr.dtype.itemsize * arr.shape[1])))
target_view = target.view(np.dtype((np.void, target.dtype.itemsize * target.shape[0])))

matches = np.in1d(arr_view, target_view)
exists = np.any(matches)
indices = np.where(matches)[0]

结果说明

  • 如果indices返回空数组,说明目标行不存在于原数组中
  • 如果有多个行和目标行完全匹配,indices会返回所有匹配的索引值
  • 注意需要保证目标行的长度和原数组的列数一致,否则会触发维度不匹配报错

内容的提问来源于stack exchange,提问作者Aurélien l

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:00:05