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

如何查找一维数组在二维Numpy数组中的行索引

查找Numpy二维数组中指定行的索引

给定二维Numpy数组:

import numpy as np
A = np.array([[6, 9, 6],
              [1, 1, 2],
              [8, 7, 3]])

目标一维数组为 [1, 1, 2],以下是几种查找其对应行索引的方法:

方法一:利用Numpy内置函数(推荐)

通过np.where结合行维度的全匹配判断,一步获取索引:

target_row = np.array([1, 1, 2])
# 逐行判断是否与目标数组完全匹配
match_rows = (A == target_row).all(axis=1)
# 获取匹配行的索引
indices = np.where(match_rows)[0]
print(indices)  # 输出: [1]
  • (A == target_row)生成布尔数组,标记每个位置的匹配状态
  • .all(axis=1)确保整行所有元素都匹配时才返回True
  • np.where提取布尔数组中True对应的索引位置

方法二:遍历数组逐行比较

如果需要更直观的逻辑,可以手动遍历每行进行比较:

target_row = np.array([1, 1, 2])
for idx, row in enumerate(A):
    if np.array_equal(row, target_row):
        print(idx)  # 输出: 1
        break
  • enumerate同时获取行索引和行内容
  • np.array_equal用于判断两个数组是否完全相等

内容的提问来源于stack exchange,提问作者Black Beard 53

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:11:38