Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy shuffle 3-D numpy array by row

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?

like image 658
Andrie Avatar asked Sep 07 '25 06:09

Andrie


2 Answers

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')
like image 143
Chris Avatar answered Sep 08 '25 20:09

Chris


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)
like image 20
Divakar Avatar answered Sep 08 '25 18:09

Divakar