2 回答

TA贡献1784条经验 获得超9个赞
您可以使用scipy.linalg中的 block_diag。
"""
>>> print(answer)
[[0 1 2 0 0 0 0 0 0]
[0 1 2 0 0 0 0 0 0]
[0 1 2 0 0 0 0 0 0]
[0 0 0 3 4 5 0 0 0]
[0 0 0 3 4 5 0 0 0]
[0 0 0 3 4 5 0 0 0]
[0 0 0 0 0 0 6 7 8]
[0 0 0 0 0 0 6 7 8]
[0 0 0 0 0 0 6 7 8]]
"""
from scipy.linalg import block_diag
import numpy as np
x = np.arange(9).reshape(3, 3)
answer = block_diag(*np.array_split(x.repeat(3, axis=0), 3))

TA贡献1815条经验 获得超6个赞
不确定它是如何 pythonic 但我的想法是使用列表理解来遍历每一行并根据更改的参数对其进行 np.pad :
import numpy as np
x = np.arange(0,9,1).reshape((3,3))
a = x.shape[1] # length of original rows | you can hardcode to 3
b = x.shape[0]*a - a # number of cells you will pad each row with | you can hardcode it to 6
repeat = 3 # how many times each row should be repeated
x_padded = [np.pad(row, (i*a, b-i*a)) for i, row in enumerate(x)]
x_out = np.repeat(x_padded, repeat, axis=0)
print(x_out)
输出:
[[0 1 2 0 0 0 0 0 0]
[0 1 2 0 0 0 0 0 0]
[0 1 2 0 0 0 0 0 0]
[0 0 0 3 4 5 0 0 0]
[0 0 0 3 4 5 0 0 0]
[0 0 0 3 4 5 0 0 0]
[0 0 0 0 0 0 6 7 8]
[0 0 0 0 0 0 6 7 8]
[0 0 0 0 0 0 6 7 8]]
添加回答
举报