[SciPy-User] indexing array without changing the ndims

Warren Weckesser warren.weckesser@enthought....
Tue Jan 26 01:00:42 CST 2010

```Gabriel Gellner wrote:
> On Mon, Jan 25, 2010 at 10:08 PM, Warren Weckesser
> <warren.weckesser@enthought.com> wrote:
>
>> Gabriel Gellner wrote:
>>
>>> I really want an easy way to index an array but not have numpy
>>> simplify the shape (if you know R I want their drop=FALSE behavior).
>>>
>>>
>> For those of us who aren't familiar with R, could you give a concrete
>> example of what you want to do?
>>
>>
> It would be the similar to what the numpy.matrix class does, namely
> when you use an index like
> `mat[0, :]` you still have ndims == 2 (a column matrix in this case).
> So I want this behavior for an ndarray so I could be certain that if I
> do any indexing the ndims of the returned array is the same as the
> original array.
>

One way you could do this is to always using a slice instead of a single
number as the index:  mat[0:1, :].  Or as in this example, where a[:,
1:2] pulls out the second column as a 2D numpy array with shape (3,1):

-----
In [1]: import numpy as np

In [2]: a = np.arange(12).reshape(3,4)

In [3]: a
Out[3]:
array([[ 0,  1,  2,  3],
[ 4,  5,  6,  7],
[ 8,  9, 10, 11]])

In [4]: a[:,1]   # a 1D slice, but not what you want.
Out[4]: array([1, 5, 9])

In [5]: a[:,1:2] # a slice with shape (3,1)
Out[5]:
array([[1],
[5],
[9]])
-----

Warren

> In R any array can be indexed with an extra keyword argument
> drop=FALSE to give this behavior so for the above I would have
> `mat[0, :, drop=False]` (in pretend python notation, in R we would
> write mat[1,, drop=F]) and it would do the right thing. An even more
> extreme example would be to do something like
>
> `zeros((3, 3, 3))[0, 0, 0, drop=False]` (In R `array(0, c(3, 3, 3))[1,
> 1, 1, drop=F]`) which would return an array with shape == (1, 1, 1)
> Now this drop notation is just for explanation, I know it is not
> possible in python, but I was hoping their is some equivalent way of
> getting this nice behavior. Looking at the matrix source code suggest
> this is not the case and it needs to be coded by hand, I was hoping
> this is not the case!
>
> thanks,
> Gabriel
> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>

```