将9x9矩阵更改为类似数独的多维数据集

问题描述 投票:0回答:1

numpy中有9x9矩阵。我需要快速方法将其更改为具有多维数据集的数独类似9x9数组(我还需要方法来反转此操作)。我附上概念图。

conceptual drawing

python numpy matrix
1个回答
0
投票

重塑,置换轴和重塑 -

In [43]: a
Out[43]: 
array([[0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8],
       [0, 1, 2, 3, 4, 5, 6, 7, 8]])

In [44]: a.reshape(3,3,3,3).swapaxes(1,2).reshape(9,9)
Out[44]: 
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8]])

在通用形状的阵列上,它将是 -

m,n = a.shape
H,W = (3,3) # block size on sudoku
out = a.reshape(m//H,H,n//W,W).swapaxes(1,2).reshape(m,n)

有关intuition behind nd-to-nd array transformation的更多信息。


如果你想从头开始,在远程数组上使用kron -

In [65]: np.kron(np.ones((3,3),dtype=int),np.arange(9).reshape(3,3))
Out[65]: 
array([[0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8],
       [0, 1, 2, 0, 1, 2, 0, 1, 2],
       [3, 4, 5, 3, 4, 5, 3, 4, 5],
       [6, 7, 8, 6, 7, 8, 6, 7, 8]])
© www.soinside.com 2019 - 2024. All rights reserved.