Search code examples
numpypermutation

Permuting entire rows in a 2d numpy array


Consider numpy array arr , shown below:

    arr = ([[1, 5, 6, 3, 3, 7],
            [2, 2, 2, 2, 2, 2],
            [0, 1, 0, 1, 0, 1],
            [4, 8, 4, 8, 4, 8],
            [1, 2, 3, 4, 5, 6]])

I want to find all row permutations of arr. NOTE: the order of elements in any given row is unchanged. It is the entire rows that are being permuted.

Because arr has 5 rows, there will be 5! = 120 permutations. I’m hoping these could be ‘stacked’ into a 3d array p, having shape (120, 5, 6):

p = [[[1, 5, 6, 3, 3, 7],
      [2, 2, 2, 2, 2, 2], 
      [0, 1, 0, 1, 0, 1],  
      [4, 8, 4, 8, 4, 8],
      [1, 2, 3, 4, 5, 6]],

     [[1, 5, 6, 3, 3, 7],
      [2, 2, 2, 2, 2, 2], 
      [0, 1, 0, 1, 0, 1],  
      [1, 2, 3, 4, 5, 6]
      [4, 8, 4, 8, 4, 8]],

       … etc …

     [[1, 2, 3, 4, 5, 6],
      [4, 8, 4, 8, 4, 8],
      [0, 1, 0, 1, 0, 1],  
      [2, 2, 2, 2, 2, 2], 
      [1, 5, 6, 3, 3, 7]]]

There is a lot of material online about permitting elements within rows, but I need help in permuting the entire rows themselves.


Solution

  • You can make use of itertools.permutations and np.argsort:

    from itertools import permutations
    out = np.array([arr[np.argsort(idx)] for idx in permutations(range(5))])
    
    print(out)
    
    [[[1 5 6 3 3 7]
      [2 2 2 2 2 2]
      [0 1 0 1 0 1]
      [4 8 4 8 4 8]
      [1 2 3 4 5 6]]
    
     [[1 5 6 3 3 7]
      [2 2 2 2 2 2]
      [0 1 0 1 0 1]
      [1 2 3 4 5 6]
      [4 8 4 8 4 8]]
    
     [[1 5 6 3 3 7]
      [2 2 2 2 2 2]
      [4 8 4 8 4 8]
      [0 1 0 1 0 1]
      [1 2 3 4 5 6]]
    
     ...
    
     [[1 2 3 4 5 6]
      [0 1 0 1 0 1]
      [4 8 4 8 4 8]
      [2 2 2 2 2 2]
      [1 5 6 3 3 7]]
    
     [[4 8 4 8 4 8]
      [1 2 3 4 5 6]
      [0 1 0 1 0 1]
      [2 2 2 2 2 2]
      [1 5 6 3 3 7]]
    
     [[1 2 3 4 5 6]
      [4 8 4 8 4 8]
      [0 1 0 1 0 1]
      [2 2 2 2 2 2]
      [1 5 6 3 3 7]]]