Home > Mobile >  Slicing 2D NumPy Array, removing first and last row and column
Slicing 2D NumPy Array, removing first and last row and column

Time:01-04

I have a 2D Numpy array of tile objects that serves as a map. The outer ring is all "wall" values to make a closed border. I want to make a copy of the inner values to iterate over without touching the outer rows and columns. I'm trying:

inner_values = map.tiles[1:-1][1:-1]

to cut off the top and bottom rows and left and right columns. My map is 100*70, and this keeps giving me an array of shape (96, 70) when I want (98, 68). How can I use slices correctly to get my inner values? Thanks!

CodePudding user response:

You are just about there...you can put all the indices inside the brackets to get what you want:

import numpy as np

a = np.ones([5, 5])
print(a)

# [[1. 1. 1. 1. 1.]
#  [1. 1. 1. 1. 1.]
#  [1. 1. 1. 1. 1.]
#  [1. 1. 1. 1. 1.]
#  [1. 1. 1. 1. 1.]]


a[1:-1, 1:-1] = 0
print(a)
# [[1. 1. 1. 1. 1.]
#  [1. 0. 0. 0. 1.]
#  [1. 0. 0. 0. 1.]
#  [1. 0. 0. 0. 1.]
#  [1. 1. 1. 1. 1.]]

Or given your dimensions:

a = np.ones([100,70])
a[1:-1, 1:-1].shape
# (98, 68)
  •  Tags:  
  • Related