使用numpy在另一个矩阵中插入矩阵,而不覆盖某些原始值

2024-09-28 17:03:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要使用numpy在另一个矩阵中插入一个矩阵

我需要插入的矩阵如下所示:

tetraminos = [[0, 1, 0], 
              [1, 1, 1]]

而另一个矩阵是这样的:

board = numpy.array([
    [6,0,0,0,0,0,0,0,0,0],
    [6,0,0,0,0,0,0,0,0,0]
])

我实际使用的代码是:

board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])] = tetraminos

我得到的问题矩阵是:

wrong_matrix = numpy.array([
        [[0,1,0,0,0,0,0,0,0,0],
        [1,1,1,0,0,0,0,0,0,0]]
])

而预期的结果是:

expected_result = numpy.array([
    [6,1,0,0,0,0,0,0,0,0],
    [1,1,1,0,0,0,0,0,0,0]
])

错误在于,由于矩阵包含0,当我将其插入新矩阵时,我丢失了第一行的第一个值(数字6),而我想保留它

完整代码:

import numpy
if __name__ == '__main__':

    board = numpy.array([
        [6,0,0,0,0,0,0,0,0,0],
        [6,0,0,0,0,0,0,0,0,0]
    ])

    tetraminos = [[0, 1, 0], [1, 1, 1]]

    board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])] = tetraminos
    print(board)

    expected_result = numpy.array([
        [6,1,0,0,0,0,0,0,0,0],
        [1,1,1,0,0,0,0,0,0,0]
    ])

    exit(1)

Tags: 代码importnumpyboardlenif错误矩阵
3条回答

您可以分两个步骤进行:

tetraminos = np.array([0, 1, 0], [1, 1, 1])
temp = board[0:0 + len(tetraminos), 0:0 + len(tetraminos[0])]                                                                                                                                                                        
board[0:0 + tetraminos.shape[0], 0:0 + tetraminos.shape[1]] = np.where(tetraminos == 0, temp, tetraminos)                                                                                                                                  

输出:

array([[6, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]])

只要您始终希望在其中输入一个常量值,就可以将您的tetramino视为掩码并使用np.putmask函数:

>>> board = np.array([[6,0,0,0,0,0,0,0,0],[6,0,0,0,0,0,0,0,0]])
>>> board
array([[6, 0, 0, 0, 0, 0, 0, 0, 0],
       [6, 0, 0, 0, 0, 0, 0, 0, 0]])
>>> tetraminos = [[0,1,0],[1,1,1]]
>>> np.putmask(board[0:len(tetraminos),0:len(tetraminos[0])], tetraminos,1)
>>> board
array([[6, 1, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0, 0]])

关于putmask的一个变体

In [243]: board = np.array([
     ...:     [6,0,0,0,0,0,0,0,0,0],
     ...:     [6,0,0,0,0,0,0,0,0,0]
     ...: ])
In [244]: tetraminos = np.array([[0, 1, 0],
     ...:               [1, 1, 1]])
In [245]: aview = board[:tetraminos.shape[0],:tetraminos.shape[1]]

使用tetraminos作为布尔值来选择aview的插槽以放置值:

In [246]: aview[tetraminos.astype(bool)]=1
In [247]: board
Out[247]: 
array([[6, 1, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 0, 0, 0, 0, 0, 0, 0]])

如果tetraminos具有其他非零值,则可以将其推广

相关问题 更多 >