3

My code currently has an array, lets say for example:

arr = np.ones((512, 512)).

There is an area of the array that interests me. I usually access it like this:

arr[50:200,150:350] #do stuff here.

I was wondering, is there some way to make a variable that holds [50:200,150:350]? This way, if I need to slightly change my mask, I can do it once, on the top of the file, instead of everywhere it is accessed.

I tried mask = [50:200,150:350], arr[mask] but Python syntax won't allow that.

Thanks for the help!

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • 3
    Relevant? https://stackoverflow.com/questions/31501806/what-does-the-slice-function-do-in-python – DavidG Jan 28 '19 at 09:28
  • Good question, Python native list and tuples can be sliced with `slice()` https://docs.python.org/dev/library/functions.html#slice but numpy has a richer interface. – Dima Tisnek Jan 28 '19 at 09:32
  • I think this is what you might be looking for: [Slicing a list using a variable, in Python](https://stackoverflow.com/a/10573523/2314737). – user2314737 Jan 28 '19 at 09:33
  • Possible duplicate of [How can I create a slice object for Numpy array?](https://stackoverflow.com/questions/38917173/how-can-i-create-a-slice-object-for-numpy-array) – Thierry Lathuille Jan 28 '19 at 09:42

1 Answers1

3

Apparently numpy extends slicing and allows multiple slice() objects, one per dimension.

import numpy
o = numpy.ones((32, 32))
print(o[3:5,3:5])

foo = slice(3,5), slice(3,5)
print(o[foo])

Both incantations produce same result :)

Dima Tisnek
  • 11,241
  • 4
  • 68
  • 120