XerXes
XerXes

Reputation: 733

Numpy slicing from variable

I'm trying to slice a numpy array using a slice that is predefined in a variable. This works:

b = fromfunction(lambda x,y: 10*x+y, (5,4),dtype=int) # Just some matrix

b[1:3,1:3]
# Output:
# array([[11, 12],
#       [21, 22]])

But what I want to do is somthing like this:

slice = "1:3,1:3"
b[slice]
# Output:
# array([[11, 12],
#       [21, 22]])

It is not important to me what type the slice-variable has, I'm just using a string as an example. How do I save a slice-specifier like that?

Upvotes: 25

Views: 13562

Answers (2)

James
James

Reputation: 3231

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

Upvotes: 17

Pierre GM
Pierre GM

Reputation: 20339

You can use the built-in slice function

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

ds = (s,s)
b[ds]

Upvotes: 32

Related Questions