[Numpy-discussion] Array slices and number of dimensions

Anne Archibald aarchiba at physics.mcgill.ca
Wed Sep 1 18:07:34 EDT 2010


On 1 September 2010 17:54, Thomas Robitaille
<thomas.robitaille at gmail.com> wrote:
> Hi,
>
> I'm trying to extract sub-sections of a multidimensional array while keeping the number of dimensions the same. If I just select a specific element along a given direction, then the number of dimensions goes down by one:
>
>>>> import numpy as np
>>>> a = np.zeros((10,10,10))
>>>> a.shape
> (10, 10, 10)
>>>> a[0,:,:].shape
> (10, 10)
>
> This makes sense to me. If I want to retain the initial number of dimensions, I can do
>
>>>> a[[0],:,:].shape
> (1, 10, 10)
>
> However, if I try and do this along two directions, I do get a reduction in the number of dimensions:
>
>>>> a[[0],:,[5]].shape
> (1, 10)
>
> I'm wondering if this is normal, or is a bug? In fact, I can get what I want by doing:
>
>>>> a[[0],:,:][:,:,[5]].shape
> (1, 10, 1)
>
> so I can get around the issue, but just wanted to check whether the issue with a[[0],:,[5]] is a bug?

No, it's not a bug. The key problem is that supplying lists does not
extract a slice - it uses fancy indexing. This implies, among other
things, that the data must be copied. When you supply two lists, that
means something very different in fancy indexing. When you are
supplying arrays in all index slots, what you get back has the same
shape as the arrays you put in; so if you supply one-dimensional
lists, like

A[[1,2,3],[1,4,5],[7,6,2]]

what you get is

[A[1,1,7], A[2,4,6], A[3,5,2]]

When you supply slices in some slots, what you get is complicated, and
maybe not well-defined. In particular, I think the fancy-indexing
dimensions always wind up at the front, and any slice dimensions are
left at the end.

In short, fancy indexing is not the way to go with your problem. I
generally use np.newaxis:

a[7,np.newaxis,:,8,np.newaxis]

but you can also use slices of length one:

a[7:8, :, 8:9]

Anne


> Thanks,
>
> Tom
>
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>



More information about the NumPy-Discussion mailing list