Slice border of 2D NumPy array by integer value

你。 提交于 2020-06-02 11:06:09

问题


I would like to slice a 2D NumPy array by an integer value, but I cannot find a way to do this properly. I need to slice the "border" of the matrix by a certain number of rows/columns.

Say the array is:

a = np.reshape(np.arange(25),(5,5))
print a

[[ 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]]

slice_val = 1

b = a[:-slice_val,:-slice_val]
print "\n", b

What I get is:

[[ 0  1  2  3]
 [ 5  6  7  8]
 [10 11 12 13]
 [15 16 17 18]]

, but I want something like this:

[[6  7  8 ]
 [11 12 13]
 [16 17 18]]

回答1:


Use

b = a[slice_val:-slice_val, slice_val:-slice_val]

to slice the borders by slice_val.




回答2:


arr=np.ones(25).reshape(5,5)
arr
slice_of_array=arr[1:4,1:4]
slice_of_array


来源:https://stackoverflow.com/questions/36411483/slice-border-of-2d-numpy-array-by-integer-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!