mindmatters mindmatters - 25 days ago 16
Python Question

Numpy index slice without losing dimension information

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.

Thanks!

Answer

It's probably easiest to do x[10,:,None] or equivalently (but more readable) x[10,:,np.newaxis].

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)

Comments