[Numpy-discussion] Question about indexing

Raul Kompass rkompass@gmx...
Thu May 29 18:36:48 CDT 2008


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]]])
-------------------------------------------

Can anyone explain this?

Thank you very much,

Raul


More information about the Numpy-discussion mailing list