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

将np.argwhere结果作为二维坐标修改数组值时出现错误

np.argwhere返回坐标修改二维数组的问题及解决办法

你遇到的问题是对numpy数组索引规则的误用:np.argwhere(array==1)返回的是形状为(n, 2)的二维数组,每一行对应一个匹配元素的(行, 列)坐标。但直接用array[coordinates]索引时,numpy会将其解析为按行批量索引后再取对应列,而非逐个定位单个元素,所以才会错误修改整行整列的元素。

错误示例回顾

import numpy as np

array = np.array([[1, 0, 1], [2, 0, 0], [2, 3, 0]])
coordinates = np.argwhere(array==1)
array[coordinates] = 3
print(array)

错误输出:

[[3 3 3]
 [2 0 0]
 [3 3 3]]

两种正确解决方法

方法1:拆分坐标为行、列一维数组

把coordinates拆成行索引和列索引分别传入,就能精准定位每个目标元素:

import numpy as np

array = np.array([[1, 0, 1], [2, 0, 0], [2, 3, 0]])
coordinates = np.argwhere(array==1)
# 拆分出行、列索引数组
array[coordinates[:, 0], coordinates[:, 1]] = 3
print(array)

正确输出:

[[3 0 3]
 [2 0 0]
 [2 3 0]]

方法2:直接使用布尔索引(更简洁高效)

如果只是修改满足条件的元素,完全不需要argwhere,直接用布尔掩码索引更直观:

import numpy as np

array = np.array([[1, 0, 1], [2, 0, 0], [2, 3, 0]])
array[array == 1] = 3
print(array)

输出同样为正确结果。

内容的提问来源于stack exchange,提问作者J.A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:05:42