Fix Python – Numpy index slice without losing dimension information


Asked By – mindmatters

I’m using numpy and want to index a row without losing the dimension information.

import numpy as np
X = np.zeros((100,10))
X.shape        # >> (100, 10)
xslice = X[10,:]
xslice.shape   # >> (10,)  

In this example xslice is now 1 dimension, but I want it to be (1,10).
In R, I would use X[10,:,drop=F]. Is there something similar in numpy. I couldn’t find it in the documentation and didn’t see a similar question asked.


Now we will see solution for issue: Numpy index slice without losing dimension information


It’s probably easiest to do x[None, 10, :] or equivalently (but more readable) x[np.newaxis, 10, :]. None or np.newaxis increases the dimension of the array by 1, so that you’re back to the original after the slicing eliminates a dimension.

As far as why it’s not the default, personally, I find that constantly having arrays with singleton dimensions gets annoying very quickly. I’d guess the numpy devs felt the same way.

Also, numpy handle broadcasting arrays very well, so there’s usually little reason to retain the dimension of the array the slice came from. If you did, then things like:

a = np.zeros((100,100,10))
b = np.zeros(100,10)
a[0,:,:] = b

either wouldn’t work or would be much more difficult to implement.

(Or at least that’s my guess at the numpy dev’s reasoning behind dropping dimension info when slicing)

This question is answered By – Joe Kington

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0