简体   繁体   中英

How can I make a padded numpy array using the first/last row/column as the pad?

I am in need of efficiently padding a numpy array on all 4 sides, using the first and last row/column as the padding data. For example, given the following:

A=np.array([[1    2   3   4],
            [5    6   7   8],
            [9   10  11  12]])

I am trying to end up with:

B=np.array([[1    1    2    3    4    4],
            [1    1    2    3    4    4],
            [5    5    6    7    8    8],
            [9    9   10   11   12   12],
            [9    9   10   11   12   12]])

Notice the original array A is located at: B[1:-1,1:-1]. I assume I could pad in one direction first (horizontal or vertical) than the other, to get the duplicated corner values. However, my vectorization/numpification is failing me. (Note: the array I am doing this with is quite large, and i need to perform this option many times, so doing it efficiently is key- I can do it with a loop, but it is quite slow).

With np.pad , you can specify the width of padding and the padding mode to apply to an array. For your example array, the edge padding mode gives the desired result:

>>> np.pad(A, 1, 'edge')
array([[ 1,  1,  2,  3,  4,  4],
       [ 1,  1,  2,  3,  4,  4],
       [ 5,  5,  6,  7,  8,  8],
       [ 9,  9, 10, 11, 12, 12],
       [ 9,  9, 10, 11, 12, 12]])

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