On Fri, May 30, 2008 at 12:36 AM, 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, 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,
Hi, I don't have time to give a comprehensive answer - but I think I can offer a simple rule. The thing you are indexing (a) is 2 dimensional, so if you provide 2 arguments to index with (ie a[something, something]) you will get single elements - if you only provide a single argument (ie a[something]) it will pull out rows corresponding to the indexing. If you want just a specific element you have to add a second argument. Also - the outer [ ]'s in your indexing operations are just the syntax for indexing. So your shape comments are wrong:
a[0,1] # shape([0,1]) = (2,) 0.767957427399 you are indexing here with two scalars, 0,1.
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]])
You are indexing here with a 1d list [0,1]. Since you don't provide a column index you get rows 0 and 1. If you do a[ [0,1] , [0,1] ] then you get element [0,0] and element [0,1]. Hope this helps, Robin