Arnav Prasad
Arnav Prasad

Reputation: 31

In Python, is there a way to save an index subset of an array to use again later?

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!

Upvotes: 3

Views: 856

Answers (1)

Dima Tisnek
Dima Tisnek

Reputation: 11781

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 :)

Upvotes: 3

Related Questions