Pad around 2D array with 1D array in clockwise manner - NumPy / Python

Viewed 90

Lets say there are two arrays:

inner_array = np.array([[3, 3, 3],
                        [6, 6, 6],
                        [9, 9, 9]])

outer_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16])

What is the cleanest way to create array that looks like this:

[[ 1,  2,  3,  4, 5],
 [16,  3,  3,  3, 6],
 [15,  6,  6,  6, 7],
 [14,  9,  9,  9, 8],
 [13, 12, 11, 10, 9]]

It would be even better if it is possible to control starting position of outer array

1 Answers

Here's one way with choosing the starting position as additional arg -

def fill_around(inner_array, outer_array, origin=0):
    outer_array = np.roll(outer_array, origin)
    m,n = inner_array.shape
    out = np.pad(inner_array,(1,1))
    
    s = np.split(outer_array, np.cumsum([n+2,m,n+2]))
    out[[0,-1]] = [s[0],s[2][::-1]]
    out[1:-1,::n+1] = np.dstack([s[3][::-1],s[1]])
    return out

Sample run for given data -

In [181]: fill_around(inner_array, outer_array)
Out[181]: 
array([[ 1,  2,  3,  4,  5],
       [16,  3,  3,  3,  6],
       [15,  6,  6,  6,  7],
       [14,  9,  9,  9,  8],
       [13, 12, 11, 10,  9]])

Set starting position -

In [8]: fill_around(inner_array, outer_array, origin=2)
Out[8]: 
array([[15, 16,  1,  2,  3],
       [14,  3,  3,  3,  4],
       [13,  6,  6,  6,  5],
       [12,  9,  9,  9,  6],
       [11, 10,  9,  8,  7]])
Related