user3345850
user3345850

Reputation: 151

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

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]]

Upvotes: 3

Views: 113

Answers (2)

B. M.
B. M.

Reputation: 18628

knowing a.shape, an other solution is :

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]])

Upvotes: 3

Divakar
Divakar

Reputation: 221534

Using 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]])

Upvotes: 5

Related Questions