1

Suppose there is an 2-dimensional numpy array (or matrix in maths) named "A", I want to swap its 1st row with another row "n". n is can be any natural number. The following codes do not work

A = np.eye(3)
n = 2
A[0], A[n] = A[n], A[0]
print(A)

you can see it gives (I show the matrix form A for simplicity)

A = 
   0, 0, 1
   0, 1, 0
   0, 0, 1

But what I want is

A =
   0, 0, 1
   0, 1, 0
   1, 0, 0

I thought about one solution is introducing another matrix "B" which is equal to "A", but "A" and "B" are different objects. Then do this

A = np.eye(3)
B = np.eye(3)
A[0], A[n] = B[n], B[0]

This can give the correct swap on A. But it needs an additional matrix "B", I don't know if it is computational efficient. Or maybe you have better idea? Thanks :)

1
  • Try A[[0,n]] = A[[n,0]] Commented Aug 26, 2016 at 15:14

3 Answers 3

4

List swapping swaps the variable through pass by reference. So, it does not work to do the inner element swapping by traditional swap by value which is a,b=b,a

Here you can do the inner list modifications. That performs one after another which eliminates the overwriting problem.

Code:

import numpy as np
A = np.eye(3)
n = 2
A[[0,n]] = A[[n,0]]
print(A)

Output:

[[ 0.  0.  1.]
 [ 0.  1.  0.]
 [ 1.  0.  0.]]
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

import numpy as np

A = np.eye(3)
A[[0, 2]] = A[[2, 0]]
print(A)

Comments

1

Sub-arrays or slices of numpy arrays create views of the data rather than copies. Sometimes numpy can detect this and prevent corruption of data. However, numpy is unable to detect when using the python idiom for swapping. You need to copy at least one of the views before swapping.

tmp = A[0].copy() 
A[0] = A[n]
A[n] = tmp

Considering you are changing most of the data in the array it may just be easier to create a new array entirely.

indices = np.arange(n+1)
indices[0], indices[n] = indices[n], indices[0] # this is okay as indices is a 1-d array 
A = A[indices] 

Comments

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.