how to randomly sample in 2D matrix in numpy

后端 未结 2 1323
感动是毒
感动是毒 2021-02-04 21:21

I have a 2d array/matrix like this, how would I randomly pick the value from this 2D matrix, for example getting value like [-62, 29.23]. I looked at the nump

2条回答
  •  清酒与你
    2021-02-04 21:57

    Just use a random index (in your case 2 because you have 3 dimensions):

    import numpy as np
    
    Space_Position = np.array(Space_Position)
    
    random_index1 = np.random.randint(0, Space_Position.shape[0])
    random_index2 = np.random.randint(0, Space_Position.shape[1])
    
    Space_Position[random_index1, random_index2]  # get the random element.
    

    The alternative is to actually make it 2D:

    Space_Position = np.array(Space_Position).reshape(-1, 2)
    

    and then use one random index:

    Space_Position = np.array(Space_Position).reshape(-1, 2)      # make it 2D
    random_index = np.random.randint(0, Space_Position.shape[0])  # generate a random index
    Space_Position[random_index]                                  # get the random element.
    

    If you want N samples with replacement:

    N = 5
    
    Space_Position = np.array(Space_Position).reshape(-1, 2)                # make it 2D
    random_indices = np.random.randint(0, Space_Position.shape[0], size=N)  # generate N random indices
    Space_Position[random_indices]  # get N samples with replacement
    

    or without replacement:

    Space_Position = np.array(Space_Position).reshape(-1, 2)  # make it 2D
    random_indices = np.arange(0, Space_Position.shape[0])    # array of all indices
    np.random.shuffle(random_indices)                         # shuffle the array
    Space_Position[random_indices[:N]]  # get N samples without replacement
    

提交回复
热议问题