[SciPy-user] manipulate arrays/matrices

David Grant david.grant at telus.net
Thu Jun 8 01:38:59 CDT 2006


On Wednesday 07 June 2006 02:22, David Douard wrote:
> On Wed, Jun 07, 2006 at 09:42:19AM +0200, Nils Wagner wrote:
> > Hi all,
> >
> > Is there a better way to interchange two rows/columns of an array ?
>
> Hi, using numpy:
>
> from numpy import *
>
> A = diag(arange(1,n+1))+diag(ones(n-2),2)+diag(ones(n-2),-2)
>
> # swap rows 1 and 3
> A[array([1,3])] = A[array([3,1])]
>
> #swap columns 1 and 3
> A[:,array([1,3])] =  A[:,array([3,1])]

Even more compact would be to just use a list for the indices:
# swap rows 1 and 3
A[[1,3]] = A[[3,1]]
#swap columns 1 and 3
A[:,[1,3]] =  A[:,[3,1]]

Or is there a reason to cast to an array for the indices?

David



More information about the SciPy-user mailing list