How to select element randomly from a numpy array in Python

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:

Image for post
Image for post

Written by

Web geek, Self-taught full-stack web developer, Learning Python, Laravel, Vuejs, UX/UI design, Nuclear Physicist PhD

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store