[SciPy-User] indexing array without changing the ndims
Tue Jan 26 01:00:42 CST 2010
Gabriel Gellner wrote:
> On Mon, Jan 25, 2010 at 10:08 PM, Warren Weckesser
> <email@example.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 : import numpy as np
In : a = np.arange(12).reshape(3,4)
In : a
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
In : a[:,1] # a 1D slice, but not what you want.
Out: array([1, 5, 9])
In : a[:,1:2] # a slice with shape (3,1)
> 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)
> instead of ().
> 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!
> SciPy-User mailing list
More information about the SciPy-User