4

Suppose I have the following 3D matrix:

1 1 1

2 2 2

3 3 3

and behind it (3rd dimension):

a a a

b b b

c c c

Defined as the following if I am correct:

import numpy as np
x = np.array([[[1,1,1], 
               [2,2,2], 
               [3,3,3]],
              [["a","a","a"],
               ["b","b","b"],
               ["c","c","c"]]])

And I want to randomly shuffle my 3D-array by row becoming something like this:

2 2 2

1 1 1

3 3 3

behind:

b b b

a a a

c c c

*Note that a always belongs to 1, b to 2 and c to 3 (same rows)

How do I achieve this?

Andrie
  • 175
  • 1
  • 12

2 Answers2

4

Using np.random.shuffle:

import numpy as np

x = np.array([[[1,1,1], 
               [2,2,2], 
               [3,3,3]],
              [["a","a","a"],
               ["b","b","b"],
               ["c","c","c"]]])

ind = np.arange(x.shape[1])
np.random.shuffle(ind)

x[:, ind, :]

Output:

array([[['1', '1', '1'],
        ['3', '3', '3'],
        ['2', '2', '2']],

       [['a', 'a', 'a'],
        ['c', 'c', 'c'],
        ['b', 'b', 'b']]], dtype='<U21')
Chris
  • 29,127
  • 3
  • 28
  • 51
1

Simply use np.random.shuffle after bringing up the second axis as the first one, as the shuffle function works along the first axis and does the shuffling in-place -

np.random.shuffle(x.swapaxes(0,1))

Sample run -

In [203]: x
Out[203]: 
array([[['1', '1', '1'],
        ['2', '2', '2'],
        ['3', '3', '3']],

       [['a', 'a', 'a'],
        ['b', 'b', 'b'],
        ['c', 'c', 'c']]], dtype='<U21')

In [204]: np.random.shuffle(x.swapaxes(0,1))

In [205]: x
Out[205]: 
array([[['3', '3', '3'],
        ['2', '2', '2'],
        ['1', '1', '1']],

       [['c', 'c', 'c'],
        ['b', 'b', 'b'],
        ['a', 'a', 'a']]], dtype='<U21')

This should be pretty efficient as we found out in this Q&A.

Alternatively, two other ways to permute axes would be -

np.moveaxis(x,0,1)
x.transpose(1,0,2)
Divakar
  • 218,885
  • 19
  • 262
  • 358