我在numpy中有9x9矩阵。我需要使用快速方法将其更改为具有多维数据集的数独类9x9数组(我也需要使用方法来反转此操作)。我附上概念图。
答案 0 :(得分: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]])