title: What is the fastest way to swap two columns and the same rows of a 2D matrix?
body: <p>I have a problem in which I need to find an optimal permutation of the columns / rows. So when I swap column i with column j, I have to swap row i and row j. The score is applied to the resulting matrix (simulated annealing).</p>
  
  <p>It works, but I wonder if it could be faster.</p>
  
  <h2>What I do</h2>
  
  <pre><code>#!/usr/bin/env python
  
  """Swap rows and colums of a square integer matrix simultaneously."""
  
  import numpy as np
  import random
  random.seed(0)
  
  
  def swap(cm, i, j):
      """
      Swap row and column i and j in-place.
  
      Examples
      --------
      &gt;&gt;&gt; cm = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
      &gt;&gt;&gt; swap(cm, 2, 0)
      array([[8, 7, 6],
             [5, 4, 3],
             [2, 1, 0]])
      """
      # swap columns
      copy = cm[:, i].copy()
      cm[:, i] = cm[:, j]
      cm[:, j] = copy
      # swap rows
      copy = cm[i, :].copy()
      cm[i, :] = cm[j, :]
      cm[j, :] = copy
      return cm
  
  
  def main(n):
      import time
      cm = np.random.randint(0, 150000, size=(n, n))
      swaps = 10**6
  
      t0 = time.time()
      for step in range(swaps):
          # Choose what to swap
          i = random.randint(0, n - 1)
          j = i
          while j == i:
              j = random.randint(0, n - 1)
          cm = swap(cm, i, j)
      t1 = time.time()
      print("{:0.2f} swaps / sec".format(swaps / (t1 - t0)))
  
  if __name__ == '__main__':
      import doctest
      doctest.testmod()
      main(369)
  </code></pre>
  
  <h2>What I've tried</h2>
  
  <ul>
  <li>The code as it is: 152642.58 swaps / sec - 158248.08 swaps / sec</li>
  <li><code>cm[:, [i, j]] = cm[:, [j, i]]</code> for swapping the columns: 90562.43 swaps / sec - 97625.79 swaps / sec</li>
  </ul>