How to select element randomly from a numpy array in Python

Panjeh
Jun 21, 2020
import numpy as np
n = 2 # for 2 random indices
indices = np.random.choice(5, n, replace=False)
print(indices)

5 means we have indices from 0 to 4.

n means number of random indices.

Then if A is an array, first we need to generate random indices among all A indices like

import numpy as np
n = 2 # for 2 random indices
indices
= np.random.choice(A.shape[0], n, replace=False)

Then we can select the elements from A corresponding to those random indices.

a_randoms = A[indices]

Sample:

--

--