Slicing matrix

Alex Martelli aleaxit at yahoo.com
Mon Apr 17 23:28:14 EDT 2006


Robert Kern <robert.kern at gmail.com> wrote:
   ...
> array([[ 0,  1,  2,  3,  4],
>        [ 5,  6,  7,  8,  9],
>        [10, 11, 12, 13, 14],
>        [15, 16, 17, 18, 19],
>        [20, 21, 22, 23, 24]])
> 
> > How do I easily slice out [0,1,2]
> 
> In [7]: p[0, :3]
> Out[7]: array([0, 1, 2])
> 
> > or [1,2,3]
> 
> In [9]: p[0, 1:4]
> Out[9]: array([1, 2, 3])
> 
> > or [2,7,12]
> 
> In [10]: p[:3, 2]
> Out[10]: array([ 2,  7, 12])
> 
> > or [7,12,17] and put it in a list?
> 
> In [11]: p[1:4, 2]
> Out[11]: array([ 7, 12, 17])

And for the "put it in a list" part, if you truly need that (which is
rarely the case), just call list(p[1:4, 2]) and so on.  BTW, all of
these work with good old Numeric just as with numarray and numpy.


Alex



More information about the Python-list mailing list