numpy random shuffle by row independently

后端 未结 5 912
悲哀的现实
悲哀的现实 2020-12-17 03:14

I have the following array:

 a= array([[  1,  2, 3],
           [  1,  2, 3],
           [  1,  2, 3])

I understand that np.random,sh

5条回答
  •  没有蜡笔的小新
    2020-12-17 03:42

    You can do it with numpy without any loop or extra function, and much more faster. E. g., we have an array of size (2, 6) and we want a sub array (2,2) with independent random index for each column.

    import numpy as np
    
    test = np.array([[1, 1],
                     [2, 2],
                     [0.5, 0.5],
                     [0.3, 0.3],
                     [4, 4],
                     [7, 7]])
    
    id_rnd = np.random.randint(6, size=(2, 2))  # select random numbers, use choice and range if don want replacement.
    new = np.take_along_axis(test, id_rnd, axis=0)
    
    Out: 
    array([[2. , 2. ],
           [0.5, 2. ]])
    

    It works for any number of dimensions.

提交回复
热议问题