Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

arrays

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!

like image 729
Arnav Prasad Avatar asked Nov 19 '25 02:11

Arnav Prasad


1 Answers

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

like image 102
Dima Tisnek Avatar answered Nov 21 '25 17:11

Dima Tisnek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!