Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change values for a section of a numpy array?

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

like image 344
Jaycob Coleman Avatar asked Apr 22 '11 23:04

Jaycob Coleman


People also ask

How do I select part of an array in NumPy?

To select an element from Numpy Array , we can use [] operator i.e. It will return the element at given index only.

How do you change an element in an array in Python?

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.


2 Answers

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.]])
like image 198
Croad Langshan Avatar answered Sep 22 '22 15:09

Croad Langshan


array2[start:end,start:end] |= array1
like image 38
YXD Avatar answered Sep 26 '22 15:09

YXD