numpy根据取值索引位置

发布时间 2023-05-25 20:05:00作者: 海_纳百川
import numpy as np

# 示例的NumPy数组
numpy_array = np.array([[1, 2, 3], [4, 5, 6], [7, 2, 9]])

# 使用np.where()函数找到元素等于2的索引位置
indices = np.where(numpy_array == 2)

# 输出索引位置
print(indices)

上述代码将输出以下结果:

(array([0, 2], dtype=int64), array([1, 1], dtype=int64))

np.where()函数返回一个元组,包含满足条件的元素的行索引和列索引。在这个例子中,元素等于2的索引位置是行索引0、列索引1,以及行索引2、列索引1。

注意:返回的索引是从0开始的。如果要获得每个匹配元素的具体坐标,可以使用np.transpose()函数来转置索引元组:

coordinates = np.transpose(indices)
print(coordinates)

这将输出:

[[0 1]
 [2 1]]

这样,我们得到了每个元素等于2的具体坐标位置。第一行的元素等于2位于行索引0、列索引1,第二行的元素等于2位于行索引2、列索引1。