[SciPy-User] indexing array without changing the ndims

josef.pktd at gmail.com josef.pktd at gmail.com
Tue Jan 26 01:59:46 EST 2010


On Tue, Jan 26, 2010 at 1:39 AM, Gabriel Gellner <ggellner at uoguelph.ca> wrote:
> On Mon, Jan 25, 2010 at 10:08 PM, Warren Weckesser
> <warren.weckesser at 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.
>
> 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]
array([[[10]]])
>>> _.shape
(1, 1, 1)

Josef

>
> thanks,
> Gabriel
> _______________________________________________
> SciPy-User mailing list
> SciPy-User at scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
>



More information about the SciPy-User mailing list