Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping Columns with NumPy arrays

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?

like image 232
Xiphias Avatar asked Jul 01 '14 10:07

Xiphias


People also ask

How do I swap columns and rows in NumPy array?

To transpose NumPy array ndarray (swap rows and columns), use the T attribute ( . T ), the ndarray method transpose() and the numpy. transpose() function.


2 Answers

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]
like image 189
Ashoka Lella Avatar answered Sep 27 '22 21:09

Ashoka Lella


When you use the x[:] = y[:] syntax with a numpy array, the values of y are copied directly into x; no temporaries are made. So when you do x[:, 1], x[:,2] = x[:, 2], x[:, 1], first the third column of x is copied directly into the second column, and then the second column is copied directly into the third.

The second column has already been overwritten by the third columns values by the time you copy the second column to the third, so you end up with the original values in the third column.

Numpy is designed to avoid copies where possible in order to improve performance. It's important to understand that list[:] returns a copy of the list, while np.array[:] returns a view of the numpy array.

like image 31
dustyrockpyle Avatar answered Sep 27 '22 23:09

dustyrockpyle