Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在二维numpy数组中随机拾取零_Python_Arrays_Numpy - Fatal编程技术网

Python 在二维numpy数组中随机拾取零

Python 在二维numpy数组中随机拾取零,python,arrays,numpy,Python,Arrays,Numpy,我有一个2d numpy数组,如下所示: board = numpy.array([[ 0, 0, 2, 2], [ 4, 0, 2, 0], [ 2, 2, 2, 2], [ 0, 0, 0, 16]]) 我想从零中选择一个,然后用其他东西替换它。我自己想出了一个解决办法,但我正在寻找更好的办法;可能使用numpy函数,如choice,但用于2d数组 zeros = np.where(board == 0) r = np.random.randi

我有一个2d numpy数组,如下所示:

board = numpy.array([[ 0,  0,  2,  2],
    [ 4,  0,  2,  0],
    [ 2,  2,  2,  2],
    [ 0,  0,  0, 16]])
我想从零中选择一个,然后用其他东西替换它。我自己想出了一个解决办法,但我正在寻找更好的办法;可能使用numpy函数,如
choice
,但用于2d数组

zeros = np.where(board == 0)
r = np.random.randint(len(zeros[0]))
z1 = zeros[0][r]
z2 = zeros[1][r]
board[z1, z2] = 2

您可以在
board==0
的位置提取索引,将其转换为线性索引,以便使用
np.random.choice
(因为此方法仅接受一维数组),然后将随机选择的线性索引转换为相应的二维索引并进行替换

import numpy as np

board = np.array([[ 0,  0,  2,  2],
                  [ 4,  0,  2,  0],
                  [ 2,  2,  2,  2],
                  [ 0,  0,  0, 16]])

zeros = np.argwhere(board == 0) # Indices where board == 0
indices = np.ravel_multi_index([zeros[:, 0], zeros[:, 1]], board.shape) # Linear indices

ind = np.random.choice(indices) # Randomly select your index to replace

board[np.unravel_index(ind, board.shape)] = 100 # Perform the replacement

>>> board
    [[  0   0   2   2]
     [  4   0   2 100]
     [  2   2   2   2]
     [  0   0   0  16]]

你用的方法看起来不错。可以加快/简化一点

Python可以很好地处理
zero
zipped的数组:

零
#是:
(数组([0,0,1,1,3,3,3],dtype=int64),
数组([0,1,1,3,0,1,2],dtype=int64))
列表(zip(*零))
#输出:
# [(0, 0), (0, 1), (1, 1), (1, 3), (3, 0), (3, 1), (3, 2)]
随机输入
随机选择(列表(zip(*零)))
# (3, 1)
返回一个2元素元组-每个轴一个索引,可用于
[]
赋值:

board[随机选择(列表(zip(*零))]=100
板
#输出:
数组([[0,0,2,2],
[  4,   0,   2,   0],
[  2,   2,   2,   2],
[  0,   0, 100,  16]])

为什么不直接使用“ind=np.random.randint(len(zeros))”而不是所有那些乱七八糟的东西呢?他就是这么做的,他要求另一个版本,可以使用
np.random.choice
。这就是我为此而想到的。首先,“他”就是我:)我没有说
np。应该使用random.choice
。我正在寻找一个替代方案,因为它不能用于多维数组。