问题
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