首页 > 解决方案 > numpy where:如何通过匹配一维数组在 3D 数组中找到 2D 数组的索引?

问题描述

a = np.array([[[1,2,3], (1,1,0,0,8)], [[1,2,3], (1,1,2,0,8)], [[1,2,3], (4,1,0,0,8)]])
where = np.where(a[:,1] == (1,1,0,0,8))
print(where)

输出:

(array([], dtype=int64),)

我希望它输出出现0的行的索引(1,1,0,0,8)

标签: pythonarraysnumpy

解决方案


NumPy 通常将元组解释为数组或数组的子集而不是元素,但您可以通过以下方式绕过它:

el = np.array([None], dtype = object)
el[0] = (1,1,0,0,8)

where = np.where( a[:,1] == el ) # outputs a tuple: (array([0], dtype=int64),)

推荐阅读