My question is a little more specific than that actually. Consider the following arrays:
from numpy import zeros, ones
array1 = ones((3, 3), bool)
array1[0][0] = 0
array1[0][2] = 0
array1[2][0] = 0
array1[2][2] = 0
array2 = zeros((12, 12), bool)
Now what I'm looking for is a way that I can refer to a 2 dimensional portion of array2 of the same proportions as array1 so that I can add the positive values from array1 to it. I know there are ways I can do this using loops, but I'd prefer to have a single statement like array2[(some way of getting a 3x3 portion of array2)] |= array1
To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.
In Python, it is also possible to change multiple elements in an array at once. To do this, you will need to make use of the slice operator and assign the sliced values a new array to replace them.
The output from an example using floats seems easier to understand:
>>> a1 = numpy.ones((3, 3))
>>> a2 = numpy.ones((12, 12))
>>> a2[:3,:3] += a1
>>> a2
array([[ 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 2., 2., 2., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
[ 2., 2., 2., 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., 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., 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.]])
Also, note you can do things like this:
>>> a2[slice(None, a1.shape[0]), slice(None, a1.shape[1])]
array([[ 2., 2., 2.],
[ 2., 2., 2.],
[ 2., 2., 2.]])
array2[start:end,start:end] |= array1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With