我有一个矩阵
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]]
答案 0 :(得分:5)
使用array-intialization
-
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]])
答案 1 :(得分:3)
了解Does not understand character buffer dtype format string ('e')
,另一个解决方案是:
a.shape
尝试:
def fill (b,shape):
a=np.zeros(shape,dtype=b.dtype)
x = a.shape[0]//b.shape[0]+1
y = a.shape[1]//b.shape[1]+1
a[::x,::y]=b
return a