Rocky Li
Rocky Li

Reputation: 5958

pad numpy array with the opposite side of itself

Suppose I have an array A:

A = np.arange(25).reshape((5,5))

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

I want to convert it to this matrix B:

array([[24, 20, 21, 22, 23, 24, 20],
       [ 4,  0,  1,  2,  3,  4,  0],
       [ 9,  5,  6,  7,  8,  9,  5],
       [14, 10, 11, 12, 13, 14, 10],
       [19, 15, 16, 17, 18, 19, 15],
       [24, 20, 21, 22, 23, 24, 20],
       [ 4,  0,  1,  2,  3,  4,  0]])

The idea is if you walk over from the original edge of A, you would encounter the opposite side. i.e. row over top would be bottom, column left of the original first column would be the last column, top left would be bottom right, etc.

I currently do it with this:

B = np.concatenate(([A[-1]], A, [A[0]]), axis=0).T
B = np.concatenate(([B[-1]], B, [B[0]]), axis=0).T

Which does the job, looks simple and is relatively straight forward, my question is, is there a built in method or other clever ways that does not require me to manually take the edges and install them? I'm not aware of np.pad being able to do this, but I might have missed something.

Upvotes: 1

Views: 204

Answers (1)

ZisIsNotZis
ZisIsNotZis

Reputation: 1740

I believe you are looking for np.pad with mode="wrap":

a = np.arange(25).reshape(5, 5)
b = np.pad(a, 1, 'wrap')
print(a)
print(b)

results in

[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]
[[24 20 21 22 23 24 20]
 [ 4  0  1  2  3  4  0]
 [ 9  5  6  7  8  9  5]
 [14 10 11 12 13 14 10]
 [19 15 16 17 18 19 15]
 [24 20 21 22 23 24 20]
 [ 4  0  1  2  3  4  0]]

Upvotes: 2

Related Questions