Noah McIlraith
Noah McIlraith

Reputation: 14292

Getting a cropped combination of 9 2D numpy arrays (only want boundaries of middle array)

I have 9 individual 2D numpy arrays that are each 3x3, I want to join at the edges like example:

111222333 111222333 111222333 444555666 444555666 444555666 777888999 777888999 777888999

Except I only want the nearby boundaries of any array that isn't the middle one, like example:

12223 45556 45556 45556 78889

Here is the code I used to generate the first example. I have been considering using another function to crop the combined array (9x9 down to 5x5 in terms of the example) but I'm concerned about performance and I don't know how to achieve that either.

Upvotes: 0

Views: 41

Answers (1)

mtrw
mtrw

Reputation: 35088

Since you know you want to drop the first and last two columns of your 9x9 array, I would just use NumPy's indexing:

>>> x = np.arange(81).reshape((9,9))
>>> x
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, 25, 26],
       [27, 28, 29, 30, 31, 32, 33, 34, 35],
       [36, 37, 38, 39, 40, 41, 42, 43, 44],
       [45, 46, 47, 48, 49, 50, 51, 52, 53],
       [54, 55, 56, 57, 58, 59, 60, 61, 62],
       [63, 64, 65, 66, 67, 68, 69, 70, 71],
       [72, 73, 74, 75, 76, 77, 78, 79, 80]])
>>> x[:,2:-2]
array([[ 2,  3,  4,  5,  6],
       [11, 12, 13, 14, 15],
       [20, 21, 22, 23, 24],
       [29, 30, 31, 32, 33],
       [38, 39, 40, 41, 42],
       [47, 48, 49, 50, 51],
       [56, 57, 58, 59, 60],
       [65, 66, 67, 68, 69],
       [74, 75, 76, 77, 78]])

x[:,2:-2] means all rows (:), drop first two and last two columns (2:-2).

Upvotes: 1

Related Questions