[Numpy-discussion] array indexing problem

Charles R Harris charlesr.harris at gmail.com
Tue Aug 29 20:11:13 EDT 2006


On 8/29/06, Rahul Kanwar <rkanwar at geol.sc.edu> wrote:
>
> Hello,
>
>    I am trying to extract a column from a 2D array here is what is have
> done:
>
> --------------------------------------------
> In [3]: a = array([[1,2,3],[1,2,3]])
>
> In [4]: a
> Out[4]:
> array([[1, 2, 3],
>        [1, 2, 3]])
>
> In [5]: a[:, 1]
> Out[5]: array([2, 2])
>
> In [6]: a[:, 1:2]
> Out[6]:
> array([[2],
>        [2]])
> --------------------------------------------
>
> when i use a[:, 1] i get a 1x2 array where as when i use a[:, 1:2] i get
> a 2x1 array. The intuitive behavior of a[:, 1] should be a 2x1 array. Am
> i doing something wrong here or is there some reason for this behavior ?


The behaviour is expected. a[:,1] is returned with one less dimension, just
as for a one dimensional array b[1] is zero dimensional (a scalar). For
instance

In [65]: int64(2).shape
Out[65]: ()

You can get what you expect using matrices:

In [67]: a = mat(arange(6).reshape(2,3))

In [68]: a[:,1]
Out[68]:
matrix([[1],
        [4]])

But generally it is best to just use arrays and get used to the conventions.

regards,
> Rahul


Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20060829/e4152cb7/attachment.html>


More information about the NumPy-Discussion mailing list