我有一个矩阵
a = [[11 12 13 14 15]
[21 22 23 24 25]
[31 32 33 34 35]
[41 42 43 44 45]
[51 52 53 54 55]]
我会这样采样
b = a[::2,::3]
b >> [[11 14]
[31 34]
[51 54]]
现在只使用 b(假设 'a' 不存在,我只知道形状) 我如何获得以下输出
x = [[11 0 0 14 0]
[0 0 0 0 0]
[31 0 0 34 0]
[0 0 0 0 0]
[51 0 0 54 0]]
最佳答案
使用数组初始化
-
def retrieve(b, row_step, col_step):
m,n = b.shape
M,N = max(m,row_step*m-1), max(n,col_step*n-1)
out = np.zeros((M,N),dtype=b.dtype)
out[::row_step,::col_step] = b
return out
样本运行-
In [150]: b
Out[150]:
array([[11, 14],
[31, 34],
[51, 54]])
In [151]: retrieve(b, row_step=2, col_step=3)
Out[151]:
array([[11, 0, 0, 14, 0],
[ 0, 0, 0, 0, 0],
[31, 0, 0, 34, 0],
[ 0, 0, 0, 0, 0],
[51, 0, 0, 54, 0]])
In [152]: retrieve(b, row_step=3, col_step=4)
Out[152]:
array([[11, 0, 0, 0, 14, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[31, 0, 0, 0, 34, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0],
[51, 0, 0, 0, 54, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0]])
In [195]: retrieve(b, row_step=1, col_step=3)
Out[195]:
array([[11, 0, 0, 14, 0],
[31, 0, 0, 34, 0],
[51, 0, 0, 54, 0]])
关于Python 插入零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47420904/