我在数组元素的子集上使用函数np.argwhere()
,但我需要它返回满足相对于原始数组的条件的元素的索引,并且没有片。有办法做到吗?
示例代码如下:
A = np.array([1,2,3,4,5,6,7,8,9])
i = [0, 3, 6, 7, 8]
np.argwhere(A[i] < 8)
Output: array([[0], [1], [2]])
我想要的输出是
数组([[0], [3], [6]])
最佳答案
np.argwhere
为您提供切片中的索引。我们已经知道如何将切片中的索引转换为数组中的索引:切片中的索引x
对应于数组中的索引i[x]
,所以我们只需要使用np.argwhere
的结果索引到i
!
A = np.array([1,2,3,4,5,6,7,8,9])
i = np.array([0, 3, 6, 7, 8])
slice_lt8 = np.argwhere(A[i] < 8)
arr_lt8 = i[slice_lt8]
arr_lt8
现在是所需的值:
array([[0],
[3],
[6]])
关于python - 在切片上使用 np.argwhere 时如何获取原始数组中的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76237096/