Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy index slice without losing dimension information

Tags:

python

numpy

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!

like image 362
mindmatters Avatar asked Aug 23 '10 20:08

mindmatters


People also ask

Does changing a slice of a NumPy array affect the original array?

Sliced numpy array does not modify original array.

What does [: None mean in NumPy?

None is an alias for NP. newaxis. It creates an axis with length 1. This can be useful for matrix multiplcation etc. >>>> import numpy as NP >>>> a = NP.arange(1,5) >>>> print a [1 2 3 4] >>>> print a.shape (4,) >>>> print a[:,None].shape (4, 1) >>>> print a[:,None] [[1] [2] [3] [4]]

What is NumPy array explain with the help of indexing and slicing operations?

Contents of ndarray object can be accessed and modified by indexing or slicing, just like Python's in-built container objects. As mentioned earlier, items in ndarray object follows zero-based index. Three types of indexing methods are available − field access, basic slicing and advanced indexing.

How does NumPy slice work?

Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: [start:end] . We can also define the step, like this: [start:end:step] .


2 Answers

Another solution is to do

X[[10],:] 

or

I = array([10]) X[I,:] 

The dimensionality of an array is preserved when indexing is performed by a list (or an array) of indexes. This is nice because it leaves you with the choice between keeping the dimension and squeezing.

like image 151
gnebehay Avatar answered Oct 17 '22 18:10

gnebehay


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

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)

like image 25
Joe Kington Avatar answered Oct 17 '22 17:10

Joe Kington