问题
I have a large 2D numpy array for which I know a pair of indices which represent one element of the array. I want to set this element and the surrounding 20×20 area equal to zero; I have attempted using a slicing technique:
s = array[x:10, y:10]
s == 0
However, although x and y are previously defined, this is an 'invalid slice'.
I would appreciate any suggestions as to how I can accomplish this as I am new to Python.
回答1:
my_array[x - 10:x + 10, y - 10:y + 10] = 0
or
s = my_array[x - 10:x + 10, y - 10:y + 10]
s[:] = 0
回答2:
I believe you mean array[x:x+10,y:y+10]
回答3:
You select multiple elements of an array A
with A[start:stop]
where start
and stop
are zero-based indices.
For a 2D Array this applies as well: A[start1:stop1, start2:stop2]
.
With the following script
import numpy as np
A = np.ones((5,5))
A
looks like this
[[ 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.]]
with
A[1:4,1:4] = 0
you get
[[ 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.]]
回答4:
Note that for the block of zeros to be centered on your x,y coordinates, it must be of odd size. For instance, the block of zeros in the following is not centered the coordinates x,y = 4,6 but on the center coordinates of that cell, that is x, y = 4.5, 5.5:
import numpy
a = numpy.ones((10,10))
x,y = 4,6
s = 2
a[x - s: x + s, y-s: y + s] = 0
array([[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 1., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 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., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]])
whereas this one is:
a = numpy.ones((10,10))
x,y = 4,6
s = 2
a[x - s: x + s + 1, y-s: y + s + 1] = 0
print a
array([[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 0., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 0., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 0., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 0., 1.],
[ 1., 1., 1., 1., 0., 0., 0., 0., 0., 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., 1., 1., 1., 1., 1., 1.]])
If the script is for pixel based image processing, this could be an important distinction.
来源:https://stackoverflow.com/questions/8066410/slicing-a-20%c3%9720-area-around-known-indices-x-y-in-a-numpy-array