[英]Problem with array[np.argwhere(array==value)]
Taking np.argwhere
as a list of coordinates in 2d leads to a wrong result.将
np.argwhere
作为二维坐标列表会导致错误的结果。 For instance:例如:
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)
Gives:给出:
[[3 3 3]
[2 0 0]
[3 3 3]]
even though only the values 1
should be changed.即使只应更改值
1
。
In [163]: array = np.array([[1, 0, 1], [2, 0, 0], [2, 3, 0]])
In [164]: array
Out[164]:
array([[1, 0, 1],
[2, 0, 0],
[2, 3, 0]])
In [165]: array==1
Out[165]:
array([[ True, False, True],
[False, False, False],
[False, False, False]])
np.where/nonzero
finds the coordinates of the True values, giving a tuple of arrays: np.where/nonzero
找到 True 值的坐标,给出 arrays 的元组:
In [166]: np.nonzero(array==1)
Out[166]: (array([0, 0], dtype=int64), array([0, 2], dtype=int64))
That tuple can be used - as is - to index the array:该元组可以按原样用于索引数组:
In [167]: array[np.nonzero(array==1)]
Out[167]: array([1, 1])
argwhere
returns the same values, but as 2d array, one column per dimension: argwhere
返回相同的值,但作为二维数组,每个维度一列:
In [168]: np.argwhere(array==1)
Out[168]:
array([[0, 0],
[0, 2]], dtype=int64)
It is wrong to use it as an index:将它用作索引是错误的:
In [169]: array[np.argwhere(array==1),:]
Out[169]:
array([[[1, 0, 1],
[1, 0, 1]],
[[1, 0, 1],
[2, 3, 0]]])
I added the :
to show more clearly that it is just indexing the first dimension of array
, not both as done with the tuple of arrays in [167].我添加了
:
以更清楚地表明它只是索引array
的第一维,而不是像 [167] 中的 arrays 元组所做的那样。
To use argwhere
to index the array we have to do:要使用
argwhere
索引我们必须做的数组:
In [170]: x = np.argwhere(array==1)
In [171]: x
Out[171]:
array([[0, 0],
[0, 2]], dtype=int64)
Apply each column separately to the dimensions:将每一列分别应用于维度:
In [172]: array[x[:,0], x[:,1]]
Out[172]: array([1, 1])
argwhere
is more useful if you want to iterate through the nonzero elements:如果您想遍历非零元素,
argwhere
更有用:
In [173]: for i in x:
...: print(array[tuple(i)])
...:
1
1
But as commented, you don't need the where/argwhere
step;但是正如所评论的那样,您不需要
where/argwhere
步骤; just use the boolean array as index只需使用 boolean 数组作为索引
In [174]: array[array==1]
Out[174]: array([1, 1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.