从numpy数组中随机选择的索引。

时间:2022-05-29 12:05:09

I have a 2-d numpy array populated with integers [-1, 0, +1]. I need to choose a random element that is not zero from it and calculate the sum of its adjacent elements.

我有一个二维的numpy数组,其中填充了整数[- 1,0,+1]。我需要选择一个不为零的随机元素并计算其相邻元素的和。

Is there a way to get the index of a numpy.random.choice?

有没有一种方法可以得到numpi .random.choice的索引?

lattice=np.zeros(9,dtype=numpy.int)
lattice[:2]=-1
lattice[2:4]=1
random.shuffle(lattice)
lattice=lattice.reshape((3,3))

random.choice(lattice[lattice!=0])

This gives the draw from the right sample, but I would need the index of the choice to be able to identify its adjacent elements. My other idea is to just sample from the index and then check if the element is non-zero, but this is obviously quite wasteful when there are a lot of zeros.

这就给出了从正确样本中抽取的结果,但是我需要选择的索引来识别它的相邻元素。我的另一个想法是从索引中抽取样本,然后检查元素是否为非零,但是当有很多0时,这显然是非常浪费的。

1 个解决方案

#1


4  

You can use lattice.nonzero() to get the locations of the nonzero elements [nonzero docs]:

您可以使用grid .nonzero()获取非零元素的位置[非零文档]:

>>> lnz = lattice.nonzero()
>>> lnz
(array([0, 0, 1, 1]), array([1, 2, 0, 1]))

which returns a tuple of arrays corresponding to the coordinates of the nonzero elements. Then you draw an index:

返回与非零元素的坐标相对应的数组元组。然后你画一个指数:

>>> np.random.randint(0, len(lnz[0]))
3

and use that to decide which coordinate you're interested in.

然后用它来决定你感兴趣的坐标。

#1


4  

You can use lattice.nonzero() to get the locations of the nonzero elements [nonzero docs]:

您可以使用grid .nonzero()获取非零元素的位置[非零文档]:

>>> lnz = lattice.nonzero()
>>> lnz
(array([0, 0, 1, 1]), array([1, 2, 0, 1]))

which returns a tuple of arrays corresponding to the coordinates of the nonzero elements. Then you draw an index:

返回与非零元素的坐标相对应的数组元组。然后你画一个指数:

>>> np.random.randint(0, len(lnz[0]))
3

and use that to decide which coordinate you're interested in.

然后用它来决定你感兴趣的坐标。