Numpy slicing from variable Numpy slicing from variable numpy numpy

Numpy slicing from variable


You can use the built-in slice function

s = slice(1,3)b[s,s]ds = (s,s)b[ds]


numpy.s_ and numpy.index_exp provide a convenient way of doing this:

the_slice = numpy.index_exp[1:3, 1:3]b[the_slice]

They can't do anything that you can't do with a combination of slice, tuples, None, and Ellipsis, but they allow you to use exactly the same syntax as you would use to slice an array (the only difference between s_ and index_exp is that for a one-dimensional slice, s_ returns a slice object, while index_exp wraps it in a tuple).