检索具有特定值的 numpy 数组中随机项的索引

use*_*577 2 python arrays random numpy

我有一个具有小范围不同值的二维 numpy 数组。我想检索一个随机索引,但具有特定值。例如说这是数组:

arr = [[1,2,1,1,3],
       [4,3,4,1,1],
       [2,3,1,2,1],
       [1,2,1,1,2],
       [3,1,3,4,2]]
Run Code Online (Sandbox Code Playgroud)

我想要一个任意值为 1 的随机索引,例如 (2,2)。到目前为止,我能够做到这一点的唯一方法是采用任何随机索引,然后检查它是否包含我想要的值,如果不包含则重绘。对于上面的例子,这没问题,但我需要从一个大数组中检索许多随机索引。

我所描述的程序是否有方法或算法?

其应用是提供分类图像的随机像素以执行精度评估。

MSe*_*ert 5

您将列表转换为 a numpy.array,然后从np.argwhere结果中随机选择一个坐标:

import numpy as np
import random
random.choice(np.argwhere(np.array(arr)==value))
Run Code Online (Sandbox Code Playgroud)