Python 插入零?

标签 python numpy

我有一个矩阵

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/

相关文章:

python - 如何使用pandas从dataframe中获取数据

python - NumPy - 从 2D numpy 数组创建 1-hot 张量

python - 如何有效地切片 numpy 数组

python - 在tkinter.treeview中选择一个单元格并获取单元格数据

python - scikit-learn 或 statsmodels 中线性回归调整参数的限制范围

python - 快速、干净地查找 Numpy 数组索引的方法

python - 连接字符串?

python - 试图从网站上抓取视频帧。获取 403 : Forbidden and 'wrong cookie'

python - 如何从字典列表中修改字典的值

python - 使用 tf.data.Dataset 使保存的模型更大