简体   繁体   中英

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

aaa

bbb

ccc

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:

bbb

aaa

ccc

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

How do I achieve this?

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')

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM