Swapping Columns with NumPy arrays

Xiphias picture Xiphias · Jul 1, 2014 · Viewed 18.1k times · Source

When I have a=1 and b=2, I can write a,b=b,a so that a and b are interchanged with each other.

I use this matrix as an array:

   [ 1,  2,  0, -2]
   [ 0,  0,  1,  2]
   [ 0,  0,  0,  0]

Swapping the columns of a numpy array does not work:

import numpy as np

x = np.array([[ 1,  2,  0, -2],
   [ 0,  0,  1,  2],
   [ 0,  0,  0,  0]])

x[:,1], x[:,2] = x[:,2], x[:,1]

It yields:

   [ 1,  0,  0, -2]
   [ 0,  1,  1,  2]
   [ 0,  0,  0,  0]

So x[:,1] has simply been overwritten and not transferred to x[:,2].

Why is this the case?

Answer

Ashoka Lella picture Ashoka Lella · Jul 1, 2014

If you're trying to swap columns you can do it by

print x
x[:,[2,1]] = x[:,[1,2]]
print x

output

[[ 1  2  0 -2]
 [ 0  0  1  2]
 [ 0  0  0  0]]
[[ 1  0  2 -2]
 [ 0  1  0  2]
 [ 0  0  0  0]]

The swapping method you mentioned in the question seems to be working for single dimensional arrays and lists though,

x =  np.array([1,2,0,-2])
print x
x[2], x[1] = x[1], x[2]
print x

output

[ 1  2  0 -2] 
[ 1  0  2 -2]