17

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?

1
  • 2
    Good question. It works as expected with regular lists, e.g. d = [0,1,2,3]; d[:2], d[2:] = d[2:], d[:2] yields [2, 3, 0, 1] Commented Jul 1, 2014 at 10:17

5 Answers 5

33

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]
Sign up to request clarification or add additional context in comments.

Comments

15

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.

Comments

1

if you need to swap the mth and the nth rows, you could you the following code:

temp = a[m,:].copy()
a[m,:]  = a[n,:]
a[n,:] =  temp

you can extrapolate the same concept for swapping the columns by changing the indices.

Comments

0

can you try something like:

arr = np.arange(10).reshape(5,2)

arr[:, [1,0]]

array([[1, 0],
       [3, 2],
       [5, 4],
       [7, 6],
       [9, 8]])

1 Comment

Works, but pay attention that this is just a view, not a copy.
-1

A very simple solution would be to use swapaxes

x = x.swapaxes(1,2)

1 Comment

Wrong, this does not swap columns, it's "sort of" a transposition. arr = np.arange(10).reshape(5,2) print(np.array_equal(arr.swapaxes(0, 1), arr.T))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.