簡體   English   中英

Python插入零?

[英]Python inserting zeros?

我有一個矩陣

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

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

了解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

試試:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM