Skip to content Skip to sidebar Skip to footer

How To Randomly Sample In 2d Matrix In Numpy

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 numpy.choice but it is bui

Solution 1:

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 arraySpace_Position[random_indices[:N]]  # get N samples without replacement

Solution 2:

Space_Position[np.random.randint(0, len(Space_Position))]
[np.random.randint(0, len(Space_Position))]

gives you what you want

Solution 3:

Refering to numpy.random.choice:

Sampling random rows from a 2-D array is not possible with this function, but is possible with Generator.choice through its axis keyword.

The genrator documentation is linked here numpy.random.Generator.choice.

Using this knowledge. You can create a generator and then "choice" from your array:

rng = np.random.default_rng()                    #creates the generator ==> Generator(PCG64) at 0x2AA703BCE50
N = 3                                            #Number of Choices
a = np.array(Space_Position)                     #makes sure, a is an ndarray and numpy-supported

s = a.shape                                      #(4,8,2)
a = a.reshape((s[0] * s[1], s[2]))               #makes your array 2 dimensional keeping the last dimension seperated
a.shape                                          #(32, 2)

b = rng.choice(a, N, axis=0, replace=False)      #returns N choices of a in array b, e.g. narray([[ 57.1 ,  11.8 ], [ 21.21,  -5.54], [ 39.04,  11.28]])#Note: replace=False prevents having the same entry several times in the result

Post a Comment for "How To Randomly Sample In 2d Matrix In Numpy"