Keith Goodman kwgoodman@gmail....
Thu May 29 19:02:28 CDT 2008

```On Thu, May 29, 2008 at 4:36 PM, Raul Kompass <rkompass@gmx.de> wrote:
> I'm new to using numpy. Today I experimented a bit with indexing
> motivated by the finding that although
> a[a>0.5]  and a[where(a>0.5)] give the same expected result (elements of
> a greater than 0.5)
> a[argwhere(a>0.5)] results in something else (rows of a in different order).
>
> I tried to figure out when indexing will yield rows and when it will
> give me an element and I could not find a simple rule.
>
> I systematically tried and got the follwing:
> ----------------------------------
>  >>> from scipy import *
>  >>> a = random.rand(10).reshape(2,5)
>  >>> a
> array([[ 0.87059263,  0.76795743,  0.13844935,  0.69040701,  0.92015062],
>       [ 0.97313123,  0.85822558,  0.8579044 ,  0.57425782,  0.57355904]])
>
>
>  >>> a[0,1]                        # shape([0,1])          = (2,)
> 0.767957427399
>
>  >>> a[[0],[1]]                    # shape([[0],[1]])      = (2, 1)
> array([ 0.76795743])
>
>  >>> a[[0,1]]                      # shape([[0,1]])        = (1, 2)
> array([[ 0.87059263,  0.76795743,  0.13844935,  0.69040701,  0.92015062],
>       [ 0.97313123,  0.85822558,  0.8579044 ,  0.57425782,  0.57355904]])
>
>  >>> a[[[0,1]]]                    # shape([[[0,1]]])      = (1, 1, 2)
> array([[ 0.87059263,  0.76795743,  0.13844935,  0.69040701,  0.92015062],
>       [ 0.97313123,  0.85822558,  0.8579044 ,  0.57425782,  0.57355904]])
>
>  >>> a[[[0],[1]]]                  # shape([[[0],[1]]])    = (1, 2, 1)
> array([ 0.76795743])
>
>  >>> a[[[0]],[[1]]]                # shape([[[0]],[[1]]])  = (2, 1, 1)
> array([[ 0.76795743]])
>
>  >>> a[[[[0,1]]]]                  # shape([[[[0,1]]]])    = (1, 1, 1, 2)
> array([[[ 0.87059263,  0.76795743,  0.13844935,  0.69040701,  0.92015062],
>        [ 0.97313123,  0.85822558,  0.8579044 ,  0.57425782,  0.57355904]]])
>
>  >>> a[[[[0],[1]]]]                # shape([[[[0],[1]]]])  = (1, 1, 2, 1)
> array([[[ 0.87059263,  0.76795743,  0.13844935,  0.69040701,  0.92015062]],
>
>       [[ 0.97313123,  0.85822558,  0.8579044 ,  0.57425782,  0.57355904]]])
>
>  >>> a[[[[0]],[[1]]]]              # shape([[[[0]],[[1]]]]) = (1, 2, 1, 1)
> array([[ 0.76795743]])
>
>  >>> a[[[[0]]],[[[1]]]]            # shape([[[[0]]],[[[1]]]]) = (2, 1, 1, 1)
> array([[[ 0.76795743]]])
> -------------------------------------------

Looks confusing to me too.

I guess it's best to take it one step at a time.

>> import numpy as np
>> a = np.arange(6).reshape(2,3)
>> a[0,1]
1

That's not surprising.

>> a[[0,1]]

That one looks odd. But it is just shorthand for:

>> a[[0,1],:]

So rows 0 and 1 and all columns.

array([[0, 1, 2],
[3, 4, 5]])

This gives the same thing:

>> a[0:2,:]

array([[0, 1, 2],
[3, 4, 5]])

Only it's not quite the same thing.

a[[0,1],:] returns a copy and a[0:2,:] returns a view

>> a[[0,1],:].flags.owndata
True
>> a[0:2,:].flags.owndata
False
```