24

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?

XerXes
  • 723
  • 1
  • 9
  • 17

2 Answers2

30

You can use the built-in slice function

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

ds = (s,s)
b[ds]
Pierre GM
  • 19,809
  • 3
  • 56
  • 67
16

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

James
  • 3,191
  • 1
  • 23
  • 39