26

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?

2 Answers 2

33

You can use the built-in slice function

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

ds = (s,s)
b[ds]
Sign up to request clarification or add additional context in comments.

Comments

18

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.