In Python 3, how to swap two sub-arrays in a 2-dimensional numpy array?
<p>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</p>

<pre><code>A = np.eye(3)
n = 2
A[0], A[n] = A[n], A[0]
print(A)
</code></pre>

<p>you can see it gives (I show the matrix form A for simplicity)</p>

<pre><code>A = 
   0, 0, 1
   0, 1, 0
   0, 0, 1
</code></pre>

<p>But what I want is</p>

<pre><code>A =
   0, 0, 1
   0, 1, 0
   1, 0, 0
</code></pre>

<p>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</p>

<pre><code>A = np.eye(3)
B = np.eye(3)
A[0], A[n] = B[n], B[0]
</code></pre>

<p>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 :)</p>

<p>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. </p>

<pre><code>tmp = A[0].copy() 
A[0] = A[n]
A[n] = tmp
</code></pre>

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

<pre><code>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] 
</code></pre>

python arrays numpy matrix