El Confuso
El Confuso

Reputation: 1981

Processing a select range of values in a numpy array

Suppose I have a 5x5 array:

import numpy as np
arr = np.random.rand(5,5)

If i want to sum the entire array I can simply have:

np.sum(arr)

How would i go about summing the values in a box defined by the upper left corner (2,2) and lower right corner (4,3)?

If this isnt clear i would like to sum the bold x's in the below array:

X X X X X

X X X X X

X X X X X

X X X X X

X X X X X

Upvotes: 1

Views: 2905

Answers (1)

gtlambert
gtlambert

Reputation: 11961

Use slicing like this:

import numpy as np
arr = np.random.rand(5,5)

# Top left 2*2 grid
np.sum(arr[:2, :2])

To sum the array in your diagram, use:

np.sum(arr[1:4, 1:3])

Upvotes: 6

Related Questions