3

My question is about array slicing in numpy. What's the logic for the following behavior?

x = arange(25)
x.shape = (5, 5)
# This results in a 2-d array in which rows and columns are excerpted from x
y = x[0:2, 0:2]
# But this results in a 1-d array
y2 = x[0:2, 0]

I would have expected y2 to be a 2-d array which contains the values in rows 0 and 1, column 0.

1
  • It is super handy to have slices like y2 be 1d arrays, For example if you want to pull out each column of an array to plot it or run it through additional signal processing, ect. Commented Oct 6, 2013 at 22:07

3 Answers 3

5

You can get your expected behavior doing x[0:2, 0:1], i.e. with a single item slice. But whenever a single element is selected, that dimension is collapsed. You may not like it, but if you think about it a little bit, you should realize it is the most consistent behavior: following your logic, x[0, 0] would be a 2d array of 1 row and 1 column, instead of the item stored at that position.

Sign up to request clarification or add additional context in comments.

Comments

4

This follows standard Python conventions. Look at the results of these analogous expressions:

>>> a = [0, 1, 2, 3, 4, 5]
>>> a[4]
4
>>> a[4:5]
[4]

As you can see, one returns one item, while the other returns a list containing one item. This is always the way python works, and numpy is just following that convention, but at a higher dimension. Whenever you pass a slice rather than an individual item, a list is returned; this is true even if there are no items in the list, either because the end index is too low, or because the starting index is too high:

>>> a[4:4]
[]
>>> a[6:6]
[]

So in all situations, passing a slice means "return a sequence (along the given dimension)," while passing an integer means "return a single item (along the given dimension)."

Comments

2

When you access an array using a single element instead of a slice, it will collapse that dimension. For that reason, if you have

x = arange(25)
y = x[10]

You would expect y to be 10 and not array([10]).

So, if you use

y2 = x[0:2, 0]
print y2.shape
(2,)

It will collapse the second dimension. If you want to keep that second dimension, you need to access that dimension using a slice.

y2 = x[0:2, 0:1]
print y2.shape
(2, 1)

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.