[SciPy-user] switch columns

Robert Kern rkern at ucsd.edu
Fri Nov 26 17:09:51 EST 2004


Alan G Isaac wrote:
> Suppose in Scipy I have a 2x2 array A and I
> want to switch the first two columns.
> I incorrectly expected the following to work:
> A[:,0],A[:,1]=A[:,1],A[:,0]
> 
> Then I discovered this works:
> A=mat(A)
> A[:,0],A[:,1]=A[:,1],A[:,0]
> 
> Question: Why the difference?
> And: how to anticipate this difference?

When A is a Numeric array, slicing it produces a view on that slice of 
the array rather than producing a copy. When you change the underlying 
array, the values in the view change as well. So when the tuple gets 
unpacked, A[:,0] gets assigned the values originally in A[:,1], then 
A[:,1] gets assigned the values currently in A[:,0] which are the values 
that were originally in A[:,1].

Apparently (I don't use the mat object, so I'm no authority here), 
slicing a mat object yields a copy, not a view.

If you explicitly want a copy of a Numeric array, use the copy() method.

   A[:,0], A[:,1] = A[:,1].copy(), A[:,0].copy()

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter




More information about the SciPy-User mailing list