[SciPy-User] indexing array without changing the ndims
Tue Jan 26 00:59:46 CST 2010
On Tue, Jan 26, 2010 at 1:39 AM, Gabriel Gellner <email@example.com> wrote:
> On Mon, Jan 25, 2010 at 10:08 PM, Warren Weckesser
> <firstname.lastname@example.org> 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.
> 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!
I use slice indices to keep (or np.newaxis, or np.expand_dims to add
the dropped dim back in)
>>> i,j,k = 0,3,2; np.arange(2*3*4).reshape(2,3,4)[i:i+1, j:j+1, k:k+1]
array(, shape=(1, 0, 1), dtype=int32)
>>> i,j,k = 0,2,2; np.arange(2*3*4).reshape(2,3,4)[i:i+1, j:j+1, k:k+1]
(1, 1, 1)
> SciPy-User mailing list
More information about the SciPy-User