简体   繁体   中英

Padding n rows and m columns of 0s to the each side of numpy array

So here's the problem

Given a 2D numpy array 'a' of sizes n×m. You need to pad the matrix with 0s so that the dimensions of the matrix become (n+2n1)×(m+2m1)

a = np.array([[1, 1], [1, 1]])
n1 = 1
m1 = 2
print(padding(a, n1, m1))
>>[[0, 0, 0, 0, 0, 0], 
  [0, 0, 1, 1, 0, 0],
  [0, 0, 1, 1, 0, 0],
  [0, 0, 0, 0, 0, 0]]

I thought solving it with the pad() function, but here is the problem with it

import numpy as np

def padding(a, n1, m1):
    return np.pad(a, [n1, m1], constant_values=0)
a = np.array([[1, 1], [1, 1]])
n1 = 1
m1 = 2
print(padding(a, n1, m1))

Result is

[[0 0 0 0 0]
  [0 1 1 0 0]
  [0 1 1 0 0]
  [0 0 0 0 0]
  [0 0 0 0 0]]

Run:

result = np.pad(a, [(n1, n1), (m1, m1)])

The second parameter ( pad_width ) is a list of 2-tuples ( before , after ) for each axis.

Padding with zeroes is the default mode, so you don't need to specify it.

The result is:

array([[0, 0, 0, 0, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 1, 1, 0, 0],
       [0, 0, 0, 0, 0, 0]])

A more concise version is:

np.pad(a, [(n1,), (m1,)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM