[英]Python inserting zeros?
I have a matrix 我有一个矩阵
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]]
I would sample it in such a way 我会以这种方式对它进行采样
b = a[::2,::3]
b >> [[11 14]
[31 34]
[51 54]]
Now only using b (assume 'a' never existed, I just know the shape) how do I get the following output 现在只使用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]]
Using array-intialization
- 使用
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
Sample runs - 样品运行 -
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]])
knowing a.shape
, an other solution is : 了解
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
Try : 试试:
In [247]: fill(b,a.shape)
Out[247]:
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]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.