1

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

El Confuso
  • 1,941
  • 6
  • 19
  • 22

1 Answers1

6

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])
gsamaras
  • 71,951
  • 46
  • 188
  • 305
gtlambert
  • 11,711
  • 2
  • 30
  • 48
  • Thanks, but I don't understand how the indices in your example `[1:4, 1:3]` are related to the 'coordinates' I want to use. I guess I dont know how this slicing works just yet. – El Confuso Sep 07 '15 at 13:10
  • For anyone else looking at this, [this answer](http://stackoverflow.com/a/4257708/3599580) is a great extension on this (correct) answer. – El Confuso Sep 07 '15 at 13:18