numpy方法,用于返回数组数组中数组出现的索引

时间:2019-07-17 13:04:25

标签: python numpy

我有一个数组数组,它​​们代表一组唯一的颜色值:

[[0.         0.         0.        ]
 [0.         0.         1.        ]
 [0.         1.         1.        ]
 [0.5019608  0.5019608  0.5019608 ]
 [0.64705884 0.16470589 0.16470589]
 [0.9607843  0.9607843  0.8627451 ]
 [1.         0.         0.        ]
 [1.         0.84313726 0.        ]
 [1.         1.         0.        ]
 [1.         1.         1.        ]]

和另一个代表一种颜色的numpy数组:

[0.9607843  0.9607843  0.8627451 ]

我需要一个函数来查找颜色集中出现在颜色集中的索引,即该函数应为上面的数组返回5。

2 个答案:

答案 0 :(得分:1)

假设这是相对较短的颜色列表(<1000),那么最简单的操作可能就是遍历列表并比较子数组的每个元素。

color_list = ...
color_index = -1
target_color = [0.9607843, 0.9607843, 0.8627451]
for i in range(0, len(color_list)):
    cur_color = color_list[i]
    if (cur_color[0] == target_color[0] and cur_color[1] = target_color[1] and cur_color[2] = target_color[2]):
        color_index = i
        break

答案 1 :(得分:1)

numpy.where()返回给定条件值在数组中的确切位置。因此,这里将如下所示(将大数组表示为 arr1 ,将寻求的矢量表示为 arr2

np.where(np.all(arr1 == arr2, axis=1))

然后返回所搜索行的行索引数组。